查询:
$query = 'INSERT INTO `menu` (`id`,`name`,`value`) VALUES (:id,:name,:value);';
参数数组:
$params = [':id' => '', ':name' => 'John', ':value' => 'ABC'];
id
是一个 PRIMARY KEY
和 AUTOINCRMENT
列。在 MySQL 中,即使传递的值是空字符串 ''
,id
列也会自动递增。这不适用于 SQLite,因为会抛出错误:
SQLSTATE[HY000]: General error: 20 datatype mismatch
当提供空字符串时,如何强制 SQLite 增加主键字段?
背景来自documentation :
On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use.
和:
If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically.
最佳答案
您应该为 auto_increment
字段传递 null
或根本不指定它。对于 mysql 来说,传递空字符串仅在某些配置设置下有效,并且有效是因为 mysql 会默默地将空字符串转换为 0
,因此您不应依赖它或期望任何其他 Rdbms 效仿。
参见 mysql 的文档no_auto_value_on_zero sql mode详情:
NO_AUTO_VALUE_ON_ZERO affects handling of AUTO_INCREMENT columns. Normally, you generate the next sequence number for the column by inserting either NULL or 0 into it. NO_AUTO_VALUE_ON_ZERO suppresses this behavior for 0 so that only NULL generates the next sequence number.
关于php - 当提供空字符串时如何强制增加主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34974194/