php - mysqli_query 数据库选择错误

标签 php mysql database select mysqli

我尝试从数据库中选择文本,但仅选择某些用户名发布的文本。基本上我需要有人查看这个 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/

相关文章:

MYSQL - 仅当 LEFT JOIN 中的行不存在时才选择

php - 根据记录是否存在使用 Laravel 查询构建器将记录插入到两个表或一个表中

php - 尝试使用 Docker 启动已安装的 Symfony "Akeneo PIM"时,EACES 权限被拒绝

php - 如何调用validation.php中编写的函数并将所有函数名称存储在数据库中

php - 如果结果集为空,MySQL 和 pdo::fetchColumn() 返回什么?

mysql - 如何在 AWS RDS 中将时区设置为 EST

php - 数据没有进入mysql

sql - 我怎样才能让一个表 "overrides"另一个?

php - 找不到错误:/

database - 在 Redis 中,如何获取 key 的到期日期?