问题
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.
- Calculate expiration date using PHP. Something like
date('Y-m-d',strtotime('+1 week')) 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