【问题标题】:Insert on first request; update on all subsequent requests在第一次请求时插入;更新所有后续请求
【发布时间】:2012-03-15 22:37:09
【问题描述】:

我正在向 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());
}
?>

就目前而言,它每次都会添加一个新行。

【问题讨论】:

  • 没关系,明白了 - 我的 SELECT 语句正在根据shelfID 调用一行。如果$shelfID 不同,它将返回 0 行。

标签: mysql insert


【解决方案1】:

您应该考虑使用 PDO 进行数据访问。这里有一个关于你需要做什么的讨论:PDO Insert on Duplicate Key Update

我会将此标记为重复,但该问题专门讨论 PDO。

【讨论】:

    【解决方案2】:

    您可以使用 INSERT ... ON DUPLICATE KEY UPDATE 语法。只要您在要插入的数据集上有唯一索引(即 userid +shelfid + bookid),它就会进行更新。

    http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

    【讨论】:

      猜你喜欢
      • 2015-03-06
      • 2018-10-27
      • 1970-01-01
      • 2013-08-22
      • 2019-02-18
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多