为什么MySQLi Fetch Array返回null?

时间:2013-01-03 00:22:05

标签: php mysqli

$query = $db->query("SELECT * FROM files WHERE hash = '" . $file . "'");
while($result = $query->fetch_array()) {
  $result[0] = $result['uploadr'];
  $result[1] = $result['name'];
}

这是查询和获取数组的代码,但它返回null。有任何想法吗?顺便说一句,我尝试使用“$ result [0]”和“$ result ['uploadr'];”来获得结果。对此有何帮助?

1 个答案:

答案 0 :(得分:-2)

不要重新分配你的阵列。只需使用$result= query->fetch_assoc()并按照以下方式检索它们:

$upload = $result['uploadr'];
echo $upload;

为了使您的查询能够抵御攻击,您应该使用预先准备好的声明:

 $query = "SELECT * FROM files WHERE hash = ?"
if (!$stmt = $db->prepare($query))
    {
        echo "Prepared Failed: (" . $db->errno . ") " . $db->error;
    }
    if (!$stmt->bind_param("s", $file))
        {
            echo "Bind Failed: (" . $db->errno . ") " . $db->error;
        }
        if (!$stmt->execute())
            {
                echo "Execution Failed: (" . $db->errno . ") " . $db->error;
            }
            if (!$results = $stmt->get_results())
                {
                    echo "No Results where found: (" . $db->errno . ") " . $db->error;
                }
                while($row = $results->fetch_assoc())
                {
                    $upload = $row['uploadr'];
                    $name = $row['name'];
                    echo $upload."<br>";
                    echo $name;
                }
        $stmt -> close();
        $db -> close();