INSERT into DB table with PDO prepare and bindParam

China☆狼群 提交于 2019-11-29 09:43:02

问题


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.

$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


回答1:


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();



回答2:


Expanding on A.O's answer, the following are also valid:

$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.




回答3:


$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();


来源:https://stackoverflow.com/questions/19599808/insert-into-db-table-with-pdo-prepare-and-bindparam

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