我正在尝试在我的网站上创建搜索功能。它没有显示任何结果,并且我不断收到 Call to a member function prepare() on a non-object in line x
...
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM entries WHERE name LIKE :searchq or description LIKE :searchq or content LIKE :searchq";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq",$searchq,PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td><a href="http://xxxx.com/xxx?id=' .$id. '" onclick="document.linkform.submit();">'.$eName.'</a></td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}
return $output;
}
}
我的functions.php 文件中包含我的PDO 连接。
最佳答案
prepare() 是 PDO 连接对象的一种方法,而您的 $conn 变量不是其中之一。它需要实例化为连接对象,如下所示:
$conn = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');
或者,如果这已经在“全局”范围内的某个地方完成,您只需在函数中声明:
global $conn;
这样做很好。该声明具有误导性。它仅在执行脚本的范围内是“全局”的,并不会超越脚本执行范围。所有此类对象都会在脚本执行结束时被销毁。和 session 无关。
关于php - 对非对象调用成员函数prepare(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22265161/