我试图弄清楚为什么这不起作用我让它只使用表单中的一个条目,然后添加电子邮件,它打破了它。 SQL注入也是安全的吗?这是错误消息
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 :(得分: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']));
答案 1 :(得分:0)
实际上,当您已单独绑定参数时,没有理由传递任何内容。只需致电
$stmt->execute();
在bindParam调用之后。
答案 2 :(得分:0)
$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']));