MySQL PDO NOW() as assigned value - is it possible?

我与影子孤独终老i 提交于 2019-12-25 03:32:55

问题


I'm trying to pass a MySQL's NOW() function into PDO's assigned value through PHP and it's failing. I found that I must pass this directly into MySQL statement. But in my case, sometimes the datetime field can be empty.

Is it even possible to pass NOW() as PHP's assigned value?

Some code:

I'm building query dynamically and the datetime is dependent on some other variable's value.

if(isset($accountStatus)&&$accountStatus!=""){
    $tmp[':account_status']=$accountStatus;
    if($accountStatus==0){
        $tmp[':vCodeExpire']="NOW() + INTERVAL 1 WEEK";
        $tmp[':verified']=0;
    }else{
        $tmp[':verified']=1;
    }
}

Building SQL query:

$sql="";
foreach($tmp as $k=>$v){
    $sql.=str_replace(":","",$k)."=".$k.",";
}
$sql=substr($sql,0,strlen($sql)-1);

Then, I run PDO query:

$db=$pdo->prepare("UPDATE users SET $sql WHERE id=:id");
$db->execute($tmp);

I tried replacing double-quotes with single-quote around NOW() + INTERVAL 1 WEEK with no luck. I also tried with single-quote around PDO query, but then $sql is passed directly, not using an assigned values.


回答1:


is it possible?

No.

There are 2 solutions.

  1. Calculate expiration date using PHP. Something like date('Y-m-d',strtotime('+1 week'))
  2. Create a conditional part for the query

    if(isset($accountStatus)&&$accountStatus!=""){
    $tmp[':account_status']=$accountStatus;
    if($accountStatus==0){
        $accSql = "NOW() + INTERVAL 1 WEEK,";
        $tmp[':verified']=0;
    }else{
        $accSql ='';
        $tmp[':verified']=1;
    }
    $db=$pdo->prepare("UPDATE users SET $accSql $sql WHERE id=:id");
    



回答2:


Use strtotime() instead of MySQL to get date values.



来源:https://stackoverflow.com/questions/15968620/mysql-pdo-now-as-assigned-value-is-it-possible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!