douqiao6563 2013-04-12 10:10
浏览 64
已采纳

MySQL PDO NOW()作为赋值 - 是否可能?

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.

  • 写回答

2条回答 默认 最新

  • doubangzhang6992 2013-04-12 10:17
    关注

    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");
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?