Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT into DB table with PDO prepare and bindParam

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

like image 604
gavin Avatar asked Oct 25 '13 21:10

gavin


People also ask

What is the difference between bindParam and bindValue?

bindParam is a PHP inbuilt function used to bind a parameter to the specified variable name in a sql statement for access the database record. bindValue, on the other hand, is again a PHP inbuilt function used to bind the value of parameter to the specified variable name in sql statement.

How to bind parameters in PHP PDO?

Parameters ¶Name of the PHP variable to bind to the SQL statement parameter. Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the type parameter. Length of the data type.

What is PDO :: Param_str?

PDO::PARAM_STR. Represents SQL character data types. For an INOUT parameter, use the bitwise OR operator to append PDO::PARAM_INPUT_OUTPUT to the type of data being bound. Set the fourth parameter, length , to the maximum expected length of the output value.


2 Answers

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();
like image 34
A.O. Avatar answered Sep 29 '22 03:09

A.O.


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.

like image 182
Sammitch Avatar answered Sep 29 '22 05:09

Sammitch