2011-01-05 90 views
8

我有一個刪除查詢,我正在運行,但只是意識到這不起作用$user_id爲空(在某些情況下會發生這種情況)。PDO編寫的語句 - NULLs

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

是否有任何變通除了具有當值爲null不同的查詢,因爲顯然只有這樣,纔能有地方正常工作與user_id IS NULL代替user_id = NULL ...

+0

我想IS NULL是乾淨的切割,並更有效地 – ajreal 2011-01-05 02:47:08

回答

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

運營商混合時要小心,以正確的括號。

如果$user_id是不是真的PHP類型null,但說,一個空字符串,你應該修改上面這樣:

... 
AND 
    (`user_id` = ? OR ? = '') 
+1

這是一個像樣的解決 – Ian 2011-01-06 04:05:18

0

快速或聲明解決了這個問題。改變這一點的代碼。

$delete = $sql->prepare(
    "DELETE_FROM 'game_player' where 'id'=? and 'user_id'=?;"); 
if ($delete->execute(array(
    $id, 
    $user_id 
)); 

更類似於以下內容。

$delete = $sql->prepare(
    "DELETE_FROM 'game_player' where ('id'=? and 'user_id'=?) 
            or ('id'=? AND 'user_id' IS NULL)"); 
if ($delete->execute(array(
    $id, 
    $user_id, 
    $id 
))) { /* success */ }