我试图从数据库中选择文本,但只选择某些用户名发布的文本。基本上我需要有人看看这个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'];
}
}
答案 0 :(得分:2)
代码中的问题是$followed
是保存SQL结果的变量。在第一次获取后,会被字符串值覆盖。下一次循环时,$followed
不再是对查询返回的结果集的引用。
还尝试从数组'user'
中检索键$row
,并且数组中不存在该键。
此外,您的代码容易受到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>";
}
}
答案 1 :(得分:0)
就像一个提示:第二个循环将结果分配给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'"