我试图插入或更新记录取决于用户ID是否存在。
我发现有两篇文章使用PDO,但似乎无法让它与我的代码一起工作。
正如您所看到的,我使用了一个if语句,使用$stmt-
还尝试:
a:userID==0
b:userID==1,if中有更新代码>
它将插入的问题,但不更新或反之亦然,这取决于我如何写它。
使用$stmt-
对非对象调用成员函数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();
}
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;