php 使用 PDO prepare 和 bindParam 插入数据库表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19599808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
INSERT into DB table with PDO prepare and bindParam
提问by gavin
In simple terms can someone explain what I am doing wrong here - I am simply trying to insert into a db with with prepare and bindParam, this is inserting 0 and Null into all the fields.
简单来说,有人可以解释我在这里做错了什么——我只是想用prepare和bindParam插入一个db,这是在所有字段中插入0和Null。
$sql = $db->prepare("INSERT INTO db_fruit VALUES (id=? ,type=? ,colour=?)");
$sql->bindParam(1, $newId);
$sql->bindParam(2, $type);
$sql->bindParam(3, $colour);
$sql->execute()
btw: this method has been working for me for UPDATE etc, but not in this case for INSERT
顺便说一句:这种方法对我来说适用于 UPDATE 等,但在这种情况下不适用于 INSERT
回答by Sammitch
Expanding on A.O's answer, the following are also valid:
扩展 AO 的答案,以下内容也有效:
$sql = $db->prepare("INSERT INTO db_fruit (id, type, colour) VALUES (? ,? ,?)");
$sql->execute(array($newId, $name, $color));
And:
和:
$sql = $db->prepare("INSERT INTO db_fruit (id, type, colour) VALUES (:id, :name, :color)");
$sql->execute(array('id' => $newId, 'name' => $name, 'color' => $color));
Might just be personal preference, but I find this syntax to be much cleaner.
可能只是个人喜好,但我发现这种语法更简洁。
回答by A.O.
Your syntax is incorrect, try this:
你的语法不正确,试试这个:
$sql = $db->prepare("INSERT INTO db_fruit (id, type, colour) VALUES (? ,? ,?)");
$sql->bindParam(1, $newId);
$sql->bindParam(2, $name);
$sql->bindParam(3, $colour);
$sql->execute();
回答by Tadeusz Majkowski
$sql = $db->prepare("INSERT INTO db_fruit (`id`, `type`, `colour`) VALUES (:id, :name, :colour)");
$sql->bindParam(':id', $newId, PDO::PARAM_INT);
$sql->bindParam(':type', $type, PDO::PARAM_INT);
$sql->bindParam(':colour', $colour, PDO::PARAM_STR);
$sql->execute();