gpt4 book ai didi

php - PDO 插入不起作用错误消息

转载 作者:行者123 更新时间:2023-11-29 08:43:27 26 4
gpt4 key购买 nike

我试图弄清楚为什么这不起作用,我让它只从表单中添加一个条目,然后添加电子邮件,然后它就破坏了它。这也能避免 SQL 注入(inject)吗?这是错误消息

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>

最佳答案

执行时绑定(bind)两个参数并跳过单独的 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']));

关于php - PDO 插入不起作用错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com