2014-08-27 92 views
1

我正在升級我的網站以使用PDO。大部分代碼工作正常,但我有一個INSERT語句,我無法工作。它適用於我的本地服務器,但不在現場。我檢查過表格結構,它們是相同的。PHP PDO INSERT與預處理語句不兼容

這是我的代碼

try { 

    foreach ($unique_product_line_ids AS $key => $value) { 

     $query_insertSQL = " 
      INSERT INTO tblCarts (
      date_created 
      , session_id 
      , product_line_id 
      , posted_by_id 
      , quantity 
      ) VALUES (
       :date_created 
      , :session_id 
      , :product_line_id 
      , :posted_by_id 
      , :quantity1 
      ) 
      ON DUPLICATE KEY UPDATE quantity = :quantity2 
        "; 
     $insertSQL = $conn->prepare($query_insertSQL); 

     $insertSQL->execute(array(
      ':date_created'=>$date_created 
      , ':session_id'=>$session_id 
      , ':product_line_id'=>$key 
      , ':posted_by_id'=>$_SESSION['member']['individual_id'] 
      , ':quantity1'=>$value 
      , ':quantity2'=>$value 
     )); 

     $rc_insertSQL = $insertSQL->rowCount(); 

     // close connection 
     $insertSQL->closeCursor(); 

    } 

} catch(PDOException $e) { 
     echo 'ERROR: ' . $e->getMessage(); 
} 

我在unique_product_line_ids陣列檢查的價值觀和他們存在的確定。我也嘗試刪除ON DUPLICATE KEY UPDATE行(及其相應的參數),但這沒有什麼區別。

我花了幾個小時試圖消除潛在的原因,並孤立問題沒有成功。任何幫助或指針將非常感激地收到。

感謝

+0

任何錯誤的錯誤?在現場安裝PDO嗎? – Sal00m 2014-08-27 09:52:36

+1

只是'echo $ insertSQL-> errorInfo()' – Sal00m 2014-08-27 09:58:20

回答

3

準備語句的優點之一是,你準備一次,多次執行,所以 我將重拍你這樣的代碼:

try { 

    $totalInserts = 0; 

    $query_insertSQL = 
    " 
     INSERT INTO tblCarts (
       date_created 
      , session_id 
      , product_line_id 
      , posted_by_id 
      , quantity 
     ) 
     VALUES (
       :date_created 
      , :session_id 
      , :product_line_id 
      , :posted_by_id 
      , :quantity 
     ) 
     ON DUPLICATE KEY UPDATE 
      quantity = :quantity 
    "; 

    $insertSQL = $conn->prepare($query_insertSQL); 


    foreach ($unique_product_line_ids AS $key => $value) 
    { 
     $insertSQL->execute(array(
       ':date_created' => $date_created 
      , ':session_id'  => $session_id 
      , ':product_line_id'=> $key 
      , ':posted_by_id' => $_SESSION['member']['individual_id'] 
      , ':quantity'  => $value 
     )); 

     $totalInserts += $insertSQL->rowCount(); 

     /** 
     * to debug if any error 
     */ 
     var_export($conn->errorInfo()); 

     // close connection - does not need anymore while you don't 
     // prepare it multiple times 
     //$insertSQL->closeCursor(); 

    } 

} 
catch(PDOException $e) 
{ 
    echo 'ERROR: ' . $e->getMessage(); 
} 


注:

您可以根據需要多次使用一個變量, 因此無需使用:quantity1:quantity2,直到它們不同。 :quantity就夠了。

要調試,如果有,您可以使用$conn->errorInfo();(連接級)或$insertSQL->errorInfo();(查詢級別)

+0

George,非常感謝您的及時響應。我已經應用提示準備一次並執行多次,並將應用於我的代碼中的其他實例。它沒有解決我的問題,但使用errorInfo方法突出了我的問題 - 拒絕連接到數據庫。真的很感謝你的幫助。約翰 – user1812108 2014-08-27 11:20:45

+1

我很高興能夠幫助你,是的,確信如果沒有發現錯誤,就很難找出確切的問題。祝你好運 – 2014-08-27 12:35:48