为什么我不能重定向浏览器到index.php页面如果'id'不存在


Why i can't redirect browser to index.php page if 'id' not existed?

我试图将不存在ID的查询重定向到主页,但总是得到由

等条目引起的错误
"<?php echo $row['script']; ?>" 

如果我甚至没有检查'$result':"未定义变量:C:'www'sts3'page.php第37行…"

require_once("php/db_connect.php"); 
if(isset($_GET['id'])) {
  if( $_GET['id'] == '' || !is_numeric($_GET['id']) )  {
    $id = 1;
  }
  else {
    $id = mysqli_real_escape_string($connection, $_GET['id']);
    $query = "SELECT * FROM content WHERE ID = '" . $id . "'";
    $result = mysqli_query($connection, $query);
    if (empty($result)) {
      header("Location:index.php"); // NOT WORKING HERE
      die();
    }
    $row = mysqli_fetch_assoc($result);
  }
}

$result不是empty,如果执行成功,您需要从$result中获取行数,以确定是否找到了结果:

if (mysqli_num_result($result) > 0) {
    header('Location: index.php');
    exit;
}

您还应该验证/过滤您的输入。

PHP提供了一组最小的验证/过滤函数:

在您的情况下,您应该过滤INT:

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) { // Validation fails. It is recommended you return an error to your user, but in this case I'm going to follow your logic.
    $id = 1;
}
// Do your database queries from here...

我认为你的问题很可能是你使用empty($result))时,$result不应该是空的,即使查询返回什么。相反,请尝试使用mysqli_num_rows:

require_once("php/db_connect.php"); 
if(isset($_GET['id'])) {
  if( $_GET['id'] == '' || !is_numeric($_GET['id']) )  {
    $id = 1;
  }
  else {
    $id = mysqli_real_escape_string($connection, $_GET['id']);
    $query = "SELECT * FROM content WHERE ID = '" . $id . "'";
    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) > 0) {
      header("Location:index.php"); // NOT WORKING HERE
      die();
    }
    $row = mysqli_fetch_assoc($result);
  }
}

$row在"if(isset($_GET['id'])) "中定义"-block,我猜只要你离开这个if-block,它就会被取消设置,因为它之前没有定义。

在一个较新的php版本中,你不能使用isset()来检查数组索引,你最好使用array_key_exists()