我有这段 PHP 代码:
if(isset($_POST['submit'])){
$likeString = '%' . $_POST['search'] . '%';
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$query->bind_param('s', $likeString);
$query->execute();
var_dump($likeString);
if (!$query) {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
if($res->num_rows > 0) {
while ($row = $res->fetch_assoc()) {
echo "<br>Title: " . $row['image_caption'];
}
} else {
echo " <br> 0 results";
}
}
var_dump($likeString)
显示了我通过搜索表单发布的单词。此外,我尝试在phpmyadmin中直接运行此查询:
SELECT * FROM images WHERE image_caption LIKE "%Volvo%"
我收到了一个正确的结果。但是在页面上我看到 0个结果
。尝试使用fetch来调试:
$res->fetch_assoc()
$res->fetchAll()
$res->fetch()
没有任何结果显示。我确信是一个非常愚蠢的简单错误,但是看不到它。请帮忙解决。
我没有遇到“在非对象上调用成员函数bind_param()”的问题,这是我从答案中进行修改时犯的错误。问题仍然存在——0个结果
更新:当前代码
$likeString = "%{$_POST['search']}%";
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ? ");
$query->bind_param('s', $likeString);
$query->execute();
if($query->num_rows > 0) {
while ($row = $query->fetch()) {
echo "<br>Title: " . $row['image_caption'];
}
} else {
echo " <br> 0 results";
}
}
更新 2:已检查数据库连接 -> 结果为 连接成功
$servername = "localhost";
$username = "mydbUsername"; // it's changed for the question
$password = "myPass"; // it's changed for the question
$dbname = "myDbName"; // it's changed for the question
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$res->num_rows > 0
为false*。 - TimSELECT * FROM images WHERE image_caption LIKE "%Volvo%"
你在phpmyadmin中试了吗?检查一下结果,还有检查一下你的连接。 - devpro