我在这里搜索了类似的问题,但无法解决我的问题。
我正在尝试向我的网站添加搜索功能,但由于某种原因搜索结果未显示。在我的error_log中,我收到此错误:
PHP致命错误:在第9行的/home/..../search.php中调用null上的成员函数prepare()
就是这一行:
<?php
require_once('includes/config.php');
include("includes/header.php");
// Search from MySQL database table
$search = $_POST['search'];
$query = $pdo->prepare("SELECT * FROM subs WHERE sub_title LIKE '%$search%' LIMIT 0, 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if(!$query->rowCount() == 0) {
echo "Search found:<br>";
echo "<table>";
echo "<tr><td>Title</td><td>Category></td><td>Language</td><td>Time</td><td>Download</td></tr>";
while($results = $query->fetch()) {
echo "<tr><td>";
echo $results['sub_title'];
echo "</td><td>";
echo $results['category'];
echo "</td><td>";
echo $results['sub_lang'];
echo "</td><td>";
echo $results['timestamp'];
echo "</td><td>";
echo $results['sub_data'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo "Nothing found";
}
?>
这是我的search.php代码:
<?php
$username = '------';
$password = '------';
try {
$conn = new PDO('mysql:host=localhost;dbname=-----', $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}
catch(PDOException $e) {
echo "Failed to connect to database!" . "<br><br>";
echo $e->getMessage();
}
?>
这是我的config.php
<form class="form-inline" action="search.php" method="POST">
<input class="form-control" name="search" id="search" type="text" placeholder="Search">
</form>
这是我在header.php
中的搜索表单No such module MyLibrary
答案 0 :(得分:0)
您正在使用:$query = $pdo->prepare
应该是:
$query = $conn->prepare()
因为我是一个懒惰的程序员,所以我创建了一个新类来节省一些时间:
class DBCommon
{
private $conn;
/** @var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}