第一次请求插入;更新所有后续请求
问题描述:
我在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());
}
?>
因为它每次都会添加一个新行。
答
您可以使用INSERT ... ON DUPLICATE KEY UPDATE语法。只要您插入的数据集(即userid + shelfid + bookid)具有唯一索引,它就会进行更新。
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
没关系,知道了 - 我的SELECT语句打电话基础上,shelfID一行。如果'$ shelfID'不同,它将返回0行。 – 2012-02-25 21:52:15