2013-07-09 57 views
0

我一直在使用準備好的插入語句幾年,並假設它正確地綁定參數或會給出一個錯誤,但它似乎不像以下PHP綁定並插入記錄沒有任何錯誤,但將應該是int的字符串更改爲零。因此,防止SQL注入攻擊可能是正確的,但最終會在表中出現虛假記錄。例如:MYSQLI準備語句bind_param類型不起作用

$q = "INSERT INTO `table` (id1, id2) VALUES (?, ?)"; 
    $stmt = mysqli_stmt_init($dbc); 
    $stmt->prepare($q); 
    $id1 = 'aaaaaaa'; 
    $id2= 'aaaaaaa'; 
    $result = $stmt->bind_param('ii', $id1, $id2); 
    echo '<p>' . $result . '</p>'; // Trying to bind a string to an int returns true! 
    echo $dbc->error; // nothing 
    $stmt->execute(); // inserts record changing $id2 to zero but auto-increments primary key $id1 
    echo $dbc->error; // nothing 

這是運行在Apache/2.2.14,PHP/5.3.1和MySQL 5.1.41的Xampp環境中。誰能告訴我發生了什麼事?

+1

我想你想檢查stmt錯誤 - '$ stmt-> error'而不是db連接錯誤'$ dbc-> error'。 – Sean

+0

對不起,這是一個錯字。 $ stmt->錯誤不會給出錯誤,但是這是預期的,因爲bind_param返回true。 bind_param錯誤報告顯然是無用的! –

回答

0

我當然不是專家,但一開始看。 您有:

$id1 = 'aaaaaaa'; 
$id2= 'aaaaaaa'; 
$result = $stmt->bind_param('ii', $id1, $id2); 

事情是你'ii'參數說你具有約束力的整數!實際上你的$id1$id2是字符串。對於你想要的字符串:

$result = $stmt->bind_param('ss', $id1, $id2); 

希望它有幫助!

0

$ stmt-> bind_param()不檢查特定類型的給定變量,它只將它們轉換爲指定的類型。而你的字符串'aaaaaaa'被轉換成一個int-value:0。這就是php的做法。

如果您的變量包含有用/正確的值,那麼數據庫插入語句是檢查錯誤的地方。如果您的驗證工作正常,則只需嘗試插入它們。

要對int進行驗證,可以使用php函數is_numeric()或is_int()。