我尝试从数据库中选择文本,但仅选择某些用户名发布的文本。基本上我需要有人查看这个 PHP 和 MySQL 代码并告诉我他们发现了什么问题。我希望我已经提供了足够的信息。另外,我收到此错误:警告:mysqli_fetch_array() 期望参数 1 为 mysqli_result,字符串给出...谢谢!这是代码:
$followed = mysqli_query($con,"SELECT followed FROM follows WHERE follower = '$username'");
while($row = mysqli_fetch_array($followed)){
echo $row['followed']."<br>";
$followed = $row['followed'];
$random = mysqli_query($con,"SELECT text FROM post WHERE user = '$followed'");
while($row = mysqli_fetch_array($random)){
echo "<ul><li id = 'stream-post'>";
echo $row['text'];
echo "</li></ul>";
$user = $row['user'];
}
}
最佳答案
代码中的问题是 $followed
是保存 SQL 结果的变量。第一次获取后,它会被字符串值覆盖。下一次循环时,$followed
不再是对查询返回的结果集的引用。
还尝试从数组 $row
中检索键 'user'
,但该键在数组中不存在。
此外,您的代码容易受到 SQL 注入(inject)攻击,并且不会检查查询返回是否成功。我们希望看到带有绑定(bind)占位符的准备好的语句,但至少,您应该对“不安全”值调用mysqli_real_escape_string
函数,并将函数的返回值包含在 SQL 文本中。
这是我更喜欢遵循的模式的示例
# set the SQL text to a variable
$sql = "SELECT followed FROM follows WHERE follower = '"
. mysqli_real_escape_string($con, $username) . "' ORDER BY 1";
# for debugging
#echo "SQL=" . $sql;
# execute the query
$sth = mysqli_query($con, $sql);
# check if query was successful, and handle somehow if not
if (!$sth) {
die mysqli_error($con);
}
while ($row = mysqli_fetch_array($sth)) {
$followed = $row['followed'];
echo htmlspecialchars($followed) ."<br>";
# set SQL text
$sql2 = "SELECT text FROM post WHERE user = '"
. mysqli_real_escape_string($con, $followed) . "' ORDER BY 1";
# for debugging
#echo "SQL=" . $sql2;
# execute the query
$sth2 = mysqli_query($con, $sql2);
# check if query execution was successful, handle if not
if (!$sth2) {
die mysqli_error($con);
}
while ($row2 = mysqli_fetch_array($sth2)) {
$text = $row2['text'];
echo "<ul><li id = 'stream-post'>" . htmlspecialchars($text) . "</li></ul>";
}
}
关于php - mysqli_query 数据库选择错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26080323/