我试图从数据库中选择文本,但只选择由某些用户名发布的文本。基本上,我需要有人查看这个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 注入的攻击,并且无法检查查询的返回是否成功。我们希望看到带有绑定占位符的预准备语句,但至少,您应该在"不安全"值上调用 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>";
}
}
作为提示:第二个循环将结果分配给已经保存第一个查询中的行的row
。使用不同的变量名称:
...
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($subrow = mysqli_fetch_array($random)){
echo "<ul><li id = 'stream-post'>";
echo $subrow['text'];
....
第二:列 user
不是 SELECT ( ... $user = $row['user'];
(
我假设,这是第二个查询:
"SELECT user, text FROM post WHERE user = '$followed'"