我一直在搜索和搜索各种各样的东西,但我无法正常工作.谁能看到我做错了什么?我是PDO的新手,并试图用其他很多东西来解决这个问题.
如果我手动提交值而不是尝试绑定它,我可以得到以下工作,但我想使用占位符.我已经得到了’Array’的值,有时MySQL响应:name导致无效的语法…我已经尝试重新排列bind的值,我只是无法让它给我回复值.我有一个插入部分,并且工作正常,但我在这里弄乱了一些东西和查询本身.
我很欣赏你可以帮助我的任何方向.这真让我抓狂:
注意:由于这只是一个测试,所有db包含的是名称和电话列(当我通过这些obsticles时会扩展).
<?PHP
# VARs
$host = "MYHOST";
$db = "MYDB";
$user = "MYUSER";
$pw = "MYPW";
# pdo options/attributes
$opts = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
# data source name
$dsn = "MysqL:host=" . $host . ";dbname=" . $db;
?>
<!DOCTYPE html>
<html>
<head><title>Test</title>
</head>
<body>
<h3>Test</h3>
<p>Pull data using PDO</p>
<form method="POST" action="test.PHP"><input type="text" name="name"><input type="submit" value="Search"></form><br /><br />
<hr />
<?
try {
$DBH = new PDO($dsn, $user, $pw, $opts);
# $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->query('SELECT name, phone FROM directory WHERE name LIKE :name');
$STH->bindParam(':name', $_POST['name']);
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['name'] . "\n" . $row['phone'] . "<br />";
}
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.<br />";
echo $e->getMessage();
# file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
?>
<hr />
</body>
</html>
– – – – – – – – – – – – – 已解决的答案 – – – – – – – – – – – – –
– – – – – – – – – – – – – 已解决的答案 – – – – – – – – – – – – –
<?
try {
$DBH = new PDO($dsn, $user, $pw, $opts);
# $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
####-------Changed query to prepare
$STH = $DBH->prepare('SELECT name, phone FROM directory WHERE name LIKE :name');
####-------using bindValue instead of bindParam
####-------also using % for wildcards to help with LIKE query (would only give specific search back without)
$STH->bindValue(':name', '%' . $_POST['name'] . '%');
####-------was missing execute (had query above instead of prepare)
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['name'] . "\n" . $row['phone'] . "<br />";
}
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.<br />";
echo $e->getMessage();
# file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
?>
解决方法:
你忘了$STH-> execute();
它应该在$STH-> bindParam(‘:name’,$_POST [‘name’])之后出现;
你还应该使用$DBH-> prepare();而不是$DBH-> query();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。