php
  • mysql
  • sql
  • 2014-04-01 54 views 0 likes 
    0

    我的PHP代碼:MySQL錯誤與`對重複KEY UPDATE`

    $stmt = $mysqli->prepare("INSERT INTO pages (name, content, in_nav, use_page, page, id) VALUES (?, ?, '$in_nav', '$use_page', ?, '$id'); ON DUPLICATE KEY UPDATE name=?, content=?, in_nav='$in_nav', use_page='$use_page', page=?"); 
    $stmt->bind_param("ssssss", $name, $body, $page, $name, $body, $page); 
    $stmt->execute(); 
    $stmt->close(); 
    

    但如果我執行它,它說:

    Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\cms\admin\cms.php on line 199

    當我嘗試$mysqli->error;它說:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON DUPLICATE KEY UPDATE name=?, content=?, in_nav='1', use_page='0', page=?' at line 1

    回答

    1

    您在ON DUPLICATE KEY UPDATE之前留下了分號,您應該將其刪除。

    正確的語法(見documentation

    INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) 
        ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b); 
    

    解決您的問題

    $stmt = $mysqli->prepare("INSERT INTO pages (name, content, in_nav, use_page, page, id) VALUES (?, ?, '$in_nav', '$use_page', ?, '$id') ON DUPLICATE KEY UPDATE name=?, content=?, in_nav='$in_nav', use_page='$use_page', page=?"); 
    

    希望這有助於:-)

    2

    )後刪除分號應該修復它

    代碼應該是這樣的

    $stmt = $mysqli->prepare("INSERT INTO pages (name, content, in_nav, use_page, page, id) VALUES (?, ?, '$in_nav', '$use_page', ?, '$id') ON DUPLICATE KEY UPDATE name=?, content=?, in_nav='$in_nav', use_page='$use_page', page=?"); 
    
    相關問題