2013-05-01 98 views
0

這裏是我當前的查詢如何使用if/else語句在UPDATE語句

UPDATE `records` SET tester1 = '$user', tester1yn = '$pass' 

我想什麼來改變這是

UPDATE `records` SET 
IF `tester1` IS NULL `tester1` = $user, AND `test1` = $pass 
ELSE `tester2` = $user, `tester1yn` = '$pass' 
WHERE `id` = $id 

但正如我有這不起作用。我有一個嵌套的問題,或者我正在做這個錯誤的方式?

UPDATE意見的基礎上

UDPATE records SET 
tester1 = if(tester1 IS NULL,'$user',tester1), 
tester1yn = if(tester1 is null, '$pass', tester1yn), 
tester2 = IF(tester1 is not null, '$user', tester2), 
tester2yn = IF(tester1 is not null,'$pass', tester2yn) 
where id = $id 

仍然還沒有實現,但。

+0

編程_guessing_不起作用。閱讀MySQL文檔以瞭解其功能。請注意,查詢是單個聲明性語句,而不是過程函數。 – 2013-05-01 20:00:13

+0

可能重複的[MYSQL IF ELSE語句在查詢?](http://stackoverflow.com/questions/8763310/mysql-if-else-statement-in-query) – 2013-05-01 20:00:31

+0

這是一個經典的MySQL注入示例,請參閱:http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php – 2013-05-01 20:01:06

回答

2

你在錯誤的方向樣的標題,雖然這個邏輯應該在未來的佈局了(在我看來)

嘗試:

UPDATE records 
SET 
tester1 = if(tester1 IS NULL,$user,tester1), 
tester1yn = IF(tester1 IS NULL,$pass,tester1yn), 
tester2 = IF(tester1 IS NOT NULL, $user,tester2), 
tester2yn = IF(tester1 IS NOT NULL,'$pass',tester2yn) 
WHERE id = $id"; 
+0

更新到這個放置仍然無法正常工作。我在所有的php變量中加上「'」,開始於$ – 2013-05-01 20:21:20

+0

不得不切換測試順序,使其正確工作。 – 2013-05-02 15:17:26

0

雖然在SQL中是可行的,但這種邏輯不應該發生在數據庫級別。用戶的登錄,認證和管理(這似乎是你以後的)應該在你的代碼中完成。

2

我沒有測試這一點,所以不要抱着我,但這應該指向你在正確的方向:

UPDATE records 
SET 
    tester1 = CASE WHEN tester1 IS NULL THEN '$user' ELSE tester1 END, 
    test1 = CASE WHEN tester1 IS NULL THEN '$pass' ELSE test1 END, 
    tester2 = CASE WHEN tester1 IS NOT NULL THEN '$user' ELSE tester2 END, 
    tester2yn = CASE WHEN tester1 IS NOT NULL THEN '$pass' ELSE tester2yn END 
WHERE 
    id = $id