2015-12-03 24 views
0

我試圖插入一些數據到數據庫中。 首先我確定我確實有數據。 我找不到原因,爲什麼沒有插入數據。插入到mysql結果重複的鍵

echo 'os_id = ', $os_id, ' os_shoph = ', $os_shoph, ' os_shopd = ', $os_shopd; 

     $insert = $db->prepare("INSERT `f2go`.`prints` (" 
        . "prt_os_id, prt_ts, prt_shoph, prt_shopd)" 
        . "VALUES (?, NOW(), ?, ?)"); 

     $insert->bind_param('iss', 
       $os_id, 
       $os_shoph, 
       $os_shopd); 

     if($insert->execute()) { 
      echo '<h1>Print new order ', $os_id, '</h1>'; 
     } else { 
      echo '<h1>Re-print order ', $os_id, '</h1>'; 
     }  
    } 

我添加了錯誤檢查。

if (!($insert = $db->prepare("INSERT `f2go`.`prints` (" 
         . "prt_os_id, prt_ts, prt_shoph, prt_shopd)" 
         . "VALUES (?, NOW(), ?, ?)"))) { 
    echo "Prepare failed: (" . $db->errno . ") " . $db->error; 
} 
if (!$insert->bind_param("iss", $os_id, $os_shoph, $os_shopd)) { 
    echo "Binding parameters failed: (" . $insert->errno . ") " . $insert->error; 
} 
if (!$insert->execute()) { 
    echo "Execute failed: (" . $insert->errno . ") " . $insert->error; 
} 

結果是:

os_id = "206" os_shoph = 0228099392 os_shopd = example 
Re-print order "206" 
Execute failed: (1062) Duplicate entry '0' for key 'prt_os_id' 

的數據庫列OS_ID被設置爲 '獨一無二' 我想不通爲什麼OS_ID = 206將被視爲 '0'

插入
+0

的OS_ID似乎有值 「206」(帶引號),而不是206 –

+0

您$ OS_ID,無論它來自與精確** 5個字符的字符串**:'」 206「'所有字符數。用一個簡單的回聲,如果你看到**「**在輸出意味着這個$ os_id包含其他字符,那麼數字。 –

+0

我試圖echo'os_id =',intval($ os_id),但這也給我也只是0 –

回答

0

在'prt_os_id'字段中'iss'的值,它似乎是一個整數字段。 此錯誤 執行失敗:(1062)鍵'prt_os_id'的重複條目'0' 引用插入查詢將'0'值置於鍵prt_os_id中,當這種情況發生兩次時,顯示此錯誤,爲什麼'0'值插入?因爲綁定中傳遞的第一個值是'iss',並且它是字符串值。應該是:

$insert->bind_param("1", $os_id, $os_shoph, $os_shopd)) 
$insert->bind_param("2", $os_id, $os_shoph, $os_shopd)) 
$insert->bind_param("3", $os_id, $os_shoph, $os_shopd)) 
$insert->bind_param("4", $os_id, $os_shoph, $os_shopd)) 

依此類推。

+0

請爲你的解決方案添加一些評論,解釋爲什麼以及如何解決問題 –

+0

'$ insert-> bind_param(「1」,.....))'你在玩什麼?這不是** Perl **。 –

0

只需從$os_id中刪除引號!

測試它

<?php 
    $os_id ='"206"'; 
    echo 'os_id = '.intval($os_id).'<br />'; 
    $os_id ="206"; 
    echo 'os_id = '.intval($os_id).'<br />'; 
    $os_id =206; 
    echo 'os_id = '.$os_id.'<br />'; 
    $os_id ="206"; 
    echo 'os_id = '.$os_id.'<br />'; 
    echo '-------------------------------------------------------------------------<br />'; 
    $os_id ='"206"'; 
    $os_id =trim($os_id, '"'); 
    echo 'os_id = '.$os_id; 
?> 

輸出:

OS_ID = 0
OS_ID = 206
OS_ID = 206
OS_ID = 206


OS_ID = 206