Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Prepared Statements - NULLs

Tags:

sql

php

null

pdo

I have a delete query that I'm running, but just realized that this doesn't work when $user_id is null (which happens in certain cases).

$id = 1;
$user_id = null;
$delete = $sql->prepare("
    DELETE FROM
        `game_player`
    WHERE
        `id` = ?
    AND
        `user_id` = ?
");
if ($delete->execute(array(
    $id,
    $user_id,
));

Is there any work around other than having different queries for when the value is null, since apparently the only way to have the where work properly is with user_id IS NULL instead of user_id = NULL...

like image 384
Ian Avatar asked Jan 05 '11 02:01

Ian


1 Answers

DELETE FROM
    `game_player`
WHERE
    `id` = ?
AND
    (`user_id` = ? OR ? IS NULL)

Be careful to parenthesis properly when mixing and with or operators.

If $user_id isn't really php type null, but say, an empty string, you should modify the above as such:

...
AND
    (`user_id` = ? OR ? = '')
like image 60
goat Avatar answered Oct 29 '22 20:10

goat