根据变量是否存在,插入OR更新记录

时间:2015-09-24 14:18:51

标签: php mysql pdo

我正在尝试insert OR update记录,具体取决于用户ID是否存在。

我发现了两篇使用PDO的帖子,但似乎无法使用我的代码。

正如您所看到的,我正在使用$stmt->rowCount() == 0的if else语句。

也尝试过:

a: userID == 0
b: userID == 1 with update in the if.

根据我的写作方式,它会插入但不会更新或反之亦然的问题。

使用$stmt->rowCount() == 0,我收到致命错误:

  

在非对象上调用成员函数rowCount()。

我是初学者,所以我可能做错了。

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();
}

1 个答案:

答案 0 :(得分:0)

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;