我有这个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 * 从图像 在哪里image_caption喜欢“%Volvo%”
我收到了1个正确的结果。在页面上,我看到0 results
。试图玩fetch:
$res->fetch_assoc()
$res->fetchAll()
$res->fetch()
他们都没有显示任何结果。我确信这是一个非常愚蠢和简单的错误,但看不到它。请帮忙。
我没有Call to a member function bind_param() on a non-object
当我从其中一个答案中提出改变时,这是我的错误。问题仍然存在 - 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:检查数据库连接 - &gt;结果是Connected successfully
$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";
答案 0 :(得分:5)
您使用的是$res
,但未定义...您必须使用$query
。
下次打开错误报告以查看这些愚蠢的错误
答案 1 :(得分:4)
试试这个:(更新你的代码)
$likeString= "%{$_POST['search']}%";
$stmt = $db->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$stmt->bind_param('s', $likeString);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
foreach ($row as $r)
{
echo "<br>Title: " . $r['image_caption'];
}
print "\n";
}
OR
<?php
$conn = new mysqli("localhost","mydbUsername","myPass","myDbName");
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$query = "SELECT * FROM images WHERE image_caption LIKE %".$_POST['search']."%";
if ($result = $conn->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo "<br> Title: ". $row["image_caption"]);
}print "\n";
/* free result set */
$result->free();
}
/* close connection */
$conn->close();
?>