2012-02-25 150 views
0

我在MySQL數據庫表中插入一行。在第一次插入時,我想要添加一個新行,但之後我只想要更新該行。這是我如何做的。 Ajax請求調用以下php文件:第一次請求插入;更新所有後續請求

<?php 

include "base.php"; 

$bookID = $_POST['bookID']; 
$shelfID = $_POST['shelfID']; 
$userID = $_SESSION['user_id']; 

$query = mysql_query("SELECT shelfID FROM shelves WHERE userID = '$userID' AND shelfID = '$shelfID' AND bookID = '$bookID'"); 

if (mysql_num_rows($query) == 0) { 
    $insert = "INSERT INTO shelves (bookID,shelfID,userID) VALUES ('$bookID','$shelfID','$userID')"; 
    mysql_query($insert) or die(mysql_error()); 
} elseif (mysql_num_rows($query) == 1) { //ie row already exists 
    $update = "UPDATE shelves SET shelfID = '$shelfID' WHERE userID = '$userID' AND bookID = '$bookID'"; 
    mysql_query($update) or die(mysql_error()); 
} 
?> 

因爲它每次都會添加一個新行。

+0

沒關係,知道了 - 我的SELECT語句打電話基礎上,shelfID一行。如果'$ shelfID'不同,它將返回0行。 – 2012-02-25 21:52:15

回答

0

您應該考慮使用PDO進行數據訪問。有一個關於你需要在這裏做什麼的討論:PDO Insert on Duplicate Key Update

我會把這個標記爲重複的,但這個問題是專門討論PDO。

相關問題