TAGS :Viewed: 21 - Published at: a few seconds ago

[ PHP Prepared Statement Fails ]

I'm passing a prepared sql insert statement (using placeholders ?, ?) into a mysql database. I'm then using ->execute($array) and passing a single array of the values in. It's working great (ie inserts) when there is data entered into every field of the form (the array is complete), however fails completly if just one single element is not completed.

With the older mysql_query, if a value was missing it would simply not insert that value into the database.

How do we deal with this in prepared statements?

Thanks!

Answer 1


They way you deal with it is to properly ensure you have entered all relevant values for your query. mysql_query() can be as lax as it wants because at the end of the day, it only has to support MySQL, but PDO is a generic interface for relational data storage and it does not take the job of making sure you've entered all your data.

Answer 2


I don't see the comparison because mysql_query doesn't take parameters?

The PDO object requires you to bind your elements to the parameters. This is the long-way:

$stmt->bindParam(":namedParam", 1, PDO::PARAM_INT);

This is short-hand, so internally PDO still should do the above with some extra work for itself:

$stmt->execute(array($value1, $value2, $etc));

If your query looks like this:

INSET INTO mytbl VALUES (?, ?, ?, ?, ?)

and your $data array looks like this:

$data = array($val1, $val2, $val3);

Where do you think the two NULL values should be inserted?
1st & 3rd ?'s ? How should PDO know that?

Furthermore, if you do know the answer to that question, you can still handle it in PHP:

function queryMyTable($val1, $val2, $val3, $val4 = null, $val5 = null) {
    ...
    $stmt->execute(array($val1, $val2, $val3, $val4, $val5));
}