天天看点

PDO预处理插入数据注意事项

如果当你使用pdo预处理插入一条数据时候,报错

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'root';
$password = '';
try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('INSERT INTO room (create_time,create_uid,exp_time,is_private) VALUES (?,?,?,?)');
$rs = $sth->execute(["2018-05-14 14:10:04",,,]);
var_dump($sth->errorInfo());exit;
           

报错

array (size=)
   => string 'HY000' (length=)
   => int 
   => string 'Field 'id' doesn't have a default value' (length=39)
           

这是由于你设计的表的主键没有auto_increment

解决方法

可以加入自增长或者预处理语句中加入主键字段