Insert auto-incremented ID using prepared statements

一笑奈何 提交于 2019-12-13 04:13:27

问题


When inserting a new record into a table with an auto-incrementing ID column, it is normally enough to give the ID field the value NULL or omit it from the INSERT query, as explained at How to insert new auto increment ID

INSERT INTO  `database`.`table` (`id`, `user`, `result`) VALUES (NULL, 'Alice', 'green')");

or

INSERT INTO  `database`.`table` (`user`, `result`) VALUES ('Alice', 'green')");

My question is - how do you do the same thing when using prepared statements. I have tried the following, using NULL:

$stmt = $db->prepare("INSERT INTO `db` (id, name, password, text) VALUES (NULL, ?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();

and the fowllowing, omitting the ID field:

$stmt = $db->prepare("INSERT INTO `test_db` (name, password, text) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();

When I run this I get nothing inserted and no error message in the browser. I think it is because it is trying to insert a duplicate value for the ID field (stackoverflow.com/questions/12179770/…) - but why it should do that when this seems equivalent to the non-prepared-statement way of inserting data, and then give no message, I'm not sure.

Any ideas most welcome!

来源:https://stackoverflow.com/questions/17592545/insert-auto-incremented-id-using-prepared-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!