使用mysql NOW()函数更新数据库中的行不能在PHP查询中工作

使用mysql NOW()函数更新数据库中的行不能在PHP查询中工作

问题描述:

I am trying to use the NOW() mysql function to update the datetime column for an inserted row. The datetime column is called 'transaction'. I tried finding a similar PHP function to mirror/mimic the datetime format but couldn't find one suitable.

 $purchase = query("INSERT INTO `Portfolio`(`id`, `symbol`, `shares`, `transaction`, `transType`) VALUES ((?),(?),(?),(?),(?)) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)",$user,$symbol,$shs,NOW(),"BUY");

我正在尝试使用NOW()mysql函数来更新插入行的datetime列。 datetime列称为“事务”。 我尝试找到一个类似的PHP函数来镜像/模仿日期时间格式,但找不到合适的。 p>

  $ purchase = query(“INSERT INTO`Component`(`id  `,`symbol`,`shares`,`transaction`,`transType`)VALUES((?),(?),(?),(?),(?))ON DUPLICATE KEY UPDATE shares = shares + VALUES( 股票)“,$ user,$ symbol,$ shs,NOW(),”BUY“); 
  code>  pre> 
  div>

You can use PHP date function:

date("Y-m-d H:i:s") 

to put current time

or you can not bind the parameter:

$purchase = query("INSERT INTO `Portfolio`(`id`, `symbol`, `shares`, transaction`, `transType`) VALUES (?,?,?,NOW(),?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)",$user,$symbol,$shs,"BUY");

The NOW() goes in place of one of the "?", not in the bind list.

If you also wanted to update that field in case the statement turns into an UPDATE, then you need it in the SET also.

$database = new database;
$now = $database->now();

class database {
...
public function now($query = "SELECT NOW();"){
        $sth = $this->connect->prepare($query);
        // execute
        if ($sth->execute()) {
            $result = $sth->fetch(PDO::FETCH_ASSOC);
            return $result["NOW()"];
        } else {
            echo "
PDO::errorInfo():
";
            print_r($sth->errorInfo());
            echo "
Query:
";
            echo $query;
            echo "
Param:
";
        }
    }
}