INSERT into DB table with PDO prepare and bindParam

gavin picture gavin · Oct 25, 2013 · Viewed 35.7k times · Source

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

Answer

Sammitch picture Sammitch · Oct 25, 2013

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.