这个问题在这里已经有了答案:
SQL - IF EXISTS UPDATE ELSE INSERT INTO
(2 个回答)
6年前关闭。
我正在尝试 insert
或 update
记录取决于用户 ID 是否存在。
我发现了两篇使用 PDO 的帖子,但似乎无法让它与我的代码一起使用。
如您所见,我正在使用 $stmt->rowCount() == 0
的 if else 语句。 .
也试过:a: userID == 0
b: userID == 1 with update in the if.
它会插入但不会更新的问题,反之亦然,具体取决于我的编写方式。
使用 $stmt->rowCount() == 0
,我收到一个 fatal error :
Call to a member function rowCount() on a non-object.
我是初学者,所以我可能做错了。
try {
if($stmt->rowCount() == 0) {
$stmt = $db->prepare('INSERT INTO books (colOne,colTwo,userID,creationDate) VALUES (:colOne, :colTwo, :userID, now())');
$stmt->execute(array(
':colOne' => $_POST['colOne'],
':colTwo' => $_POST['colTwo'],
':userID' => $_POST['userID']
));
} else {
$stmt = $db->prepare('UPDATE books SET colOne = :colOne, colTwo = :colTwo, userID = :userID, modifiedDate = NOW() WHERE userID = :userID');
$stmt->execute(array(':colOne'=>$colOne, ':colTwo'=>$colTwo, ':userID'=>$userID));
}
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
最佳答案
rowCount() 不会给您获取的记录数,因为它返回受最后一条 SQL 语句影响的行数。
详情见:http://sg3.php.net/manual/en/pdostatement.rowcount.php
你可以尝试这样的事情:
$sql = "SELECT COUNT(*) FROM TABLE WHERE CONDITION";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* UPDATE */
} else {
/* INSERT */
}
}
$res = null;
$conn = null;
关于php - 根据变量是否存在插入或更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32763785/