当表列为空时,php中的未定义索引错误

时间:2017-12-31 01:41:39

标签: php mysqli

为什么当我的表中没有记录时,下面的代码会有未定义的索引错误?

$id = $_GET['id'];
$result = mysqli_query($conn, "SELECT * FROM movies WHERE id='$id'") or die(mysqli_error($conn));

$encoded = array();
while($res = mysqli_fetch_assoc($result)) {

    $row = array(
        'id' => (int)$res['id'],
        'movies' => array (
            'social' => $res['social'],
        )
    );

    $encoded[] = $row;
}

echo json_encode($encoded)

当你在表中有更大的数据时,我认为这很危险,如果1-2列为空,事情可能会中断。

1 个答案:

答案 0 :(得分:0)

在你之前使用if($ result)并设置$ encoded = null;

这应该确保在没有结果的情况下不尝试while而在这种情况下编码变量被预设为null