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
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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With