我一直在搜索和搜索并尝试各种东西,但我无法让它正常工作。谁能看到我做错了什么?我对 PDO 很陌生,并试图通过许多其他事情来解决这个问题。
如果我手动提交一个值而不是尝试绑定它,我可以获得以下工作,但我想使用占位符。我得到了一个 'Array' 的值,有时 MySQL 会响应 :name 导致无效的语法...我尝试重新排列 bind 的值,但我无法让它返回值。我有一个插入部分,它工作正常,但我在这里搞砸了一些东西和查询本身。
我很感激你能帮助我的任何方向。这真让我抓狂:
注意:由于这只是一个测试,所有 db 包含的是名称和电话列(当我通过这些障碍时会扩展)。
<?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>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
感谢以下回复,这是对我的查询和 pdo 布局的更正:
<?
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);
}
?>