如果存在則嘗試更新記錄(時間戳),如果不存在則插入新記錄。
表是:
id = int 12 primary key, auto increment
userid = int 12
viewerid = int 12
viewDateTime = TIMESTAMP
此 sql 在 phpmyadmin 中有效,但在 php 中無效
SELECT @id := id FROM `profileViews` WHERE `userid` = 31 AND `viewerid` = 30 LIMIT 1;
REPLACE INTO `profileViews`(id, `userid`, `viewerid`, `viewDateTime`)
VALUES (@id, 31, 30, now());
這是php版本:
$INSERTViewSQL = "SELECT @id := id FROM `profileViews` WHERE `userid` = ? AND `viewerid` = ? LIMIT 1;
REPLACE INTO `profileViews`(id, `userid`, `viewerid`, `viewDateTime`)
VALUES (@id, ?, ?, now());";
try{
$DBConnection->prepare($INSERTViewSQL)->execute([$profileid, $_SESSION["id"], $profileid, $_SESSION["id"]]);
} catch(PDOException $e) {
file_put_contents($ErrorLogFileForPDO, 'update view : ' .$e->getMessage()."\n", FILE_APPEND);
}
這是錯誤訊息:
更新視圖:SQLSTATE [42000]:語法錯誤或訪問沖突:1064 您的 SQL 語法有錯誤;檢查與您的 MySQL 服務器版本相對應的手冊,以在第 2 行的 'REPLACE INTO profileViews(id, userid, viewerid, viewDateTime) VALUES (@i'附近使用正確的語法
謝謝??
uj5u.com熱心網友回復:
MySQL檔案說:
準備好的陳述句的 SQL 語法不支持多陳述句(即,單個字串中的多個陳述句由 ; 字符分隔)。
所以你需要先獲取 id 值,然后執行替換陳述句。
$stmt = $DBConnection
->prepare("SELECT id FROM ...");
$stmt->execute([$profileid, $_SESSION["id"]]);
$id = $stmt->fetchColumn();
$DBConnection
->prepare("REPLACE INTO ...");
->execute([$id, $profileid, $_SESSION["id"]]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/519448.html
標籤:phpmysqlpdo
