2012-10-31 55 views
0

我想弄清楚爲什麼這將無法正常工作我曾與添加只有一個條目表單,然後添加電子郵件,它打破了它。這也是從SQL注入安全嗎?以下是錯誤消息PDO插入不工作的錯誤消息

ERROR: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens 

這裏是我的insert.php代碼:

<?php 

try { 
$conn = new PDO('mysql:host=localhost;dbname=info', 'blah', 'test'); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$stmt = $conn->prepare('INSERT INTO people (name, email) VALUES (:name, :email)'); 
$stmt->bindParam(':name', $POST_['name']); 
$stmt->bindParam(':email', $_POST['email']); 
$stmt->execute(array(':name' => $_POST['name'])); 
$stmt->execute(array(':email' => $_POST['email'])); 
#If one or more rows were returned... 

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

?> 

這裏是工作的代碼,如果我從插入的形式只有一個值:

<?php 

try { 
$conn = new PDO('mysql:host=localhost;dbname=encorem2_info', 'encorem2', 'Yamaha!32088!'); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$stmt = $conn->prepare('INSERT INTO people (name) VALUES (:name)'); 

$stmt->execute(array(':name' => $_POST['name'])); 

#If one or more rows were returned... 

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

?> 

這是我在單獨的文件中的html代碼:

<!DOCTYPE html> 

<html> 
    <head> 
     <title>Welcome!</title> 

    </head> 
    <body> 

<form action="insert.php" method="post"> 
Name: <input type="text" name="name" id="name" /> 
Email: <input type="text" name="email" id="email"/> 
<input type="submit" /> 
</form> 

    </body> 

</html> 
+0

會發生什麼事,如果你刪除bindParams – case1352

+0

同樣的事情,我一直在嘗試各種不同的方法,但仍然沒有運氣 – Yamaha32088

回答

2

執行時綁定兩個參數,並跳過單獨的bindParam()調用。

$stmt->bindParam(':name', $POST_['name']); 
$stmt->bindParam(':email', $_POST['email']); 
$stmt->execute(array(':name' => $_POST['name'])); 
$stmt->execute(array(':email' => $_POST['email'])); 

應該只是

$stmt->execute(array(':name' => $_POST['name'], ':email' => $_POST['email'])); 
+0

PERFECT!謝謝 – Yamaha32088

0

其實沒有理由來傳遞任何東西的時候,你已經綁定單獨的參數來執行。只需撥打

$stmt->execute(); 

在bindParam調用之後。

0

您需要將您的數據傳入bindParamexecute。它會更簡單,以取代

$stmt->bindParam(':name', $POST_['name']); 
$stmt->bindParam(':email', $_POST['email']); 
$stmt->execute(array(':name' => $_POST['name'])); 
$stmt->execute(array(':email' => $_POST['email'])); 

$stmt->execute(array(':name' => $_POST['name'],':email' => $_POST['email']));