我在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 :(得分:0)
您应该考虑使用PDO进行数据访问。您需要在此处讨论:PDO Insert on Duplicate Key Update
我将此标记为重复,但该问题专门讨论PDO。
答案 1 :(得分:0)
您可以使用INSERT ... ON DUPLICATE KEY UPDATE语法。只要您要插入的数据集(即userid + shelfid + bookid)上有唯一索引,它就会进行更新。
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html