将有效变量传递给查询时出现问题

I'm passing variables to my page page?title=fred but I would like to redirect to another page if it's the wrong value(not in the database) ex: fredd


The first part checks if the variable is empty. Which seems to be working.

//get variable from title
if(!isset($_GET['title']) || empty($_GET['title'])) {
    echo "no variable";
} 
else {
    $get_title = mysqli_real_escape_string($db, $_GET['title']);
    $title = str_replace("-"," ", $get_title);
} 


I'm having trouble checking if the variable I pass is in the database and if it's not to redirect to main page.

$query = mysqli_query($db, "SELECT title FROM persons WHERE title = '$title'");
//check that variable is in the database
if(!isset($query)){
  while($row = mysqli_fetch_assoc($query)){

    echo $row['title'];

  }
// mysqli_free_result($query);
} 
else {echo "variable does not exist";} ?>


Can someone please show me what I am doing wrong and how to fix it? Thank you,

if(!isset($query)){

$query is always set (you just set it) so the code you want will never execute.

You want this instead:

if (!$query) {
  echo "Query returned error";
} else if (mysqli_num_rows($query) < 1) {
  echo "Variable does not exist";
} else {
  while ($row = mysqli_fetch_assoc($query)){
    echo $row['title'];
  }
}

isset($query) will ALWAYS be true - mysqli_query() will always returning SOMETHING, even if it's just a boolean false value.

$result = mysqli_query(..);
if ($result === false) {
    die(mysqli_error());
}
if (mysqli_num_rows($result) == 0) {
   echo "variable does not exist";
} else {
   while(...) {
      ...
   }
}