0

I've got a php search connected to mysql database, it was working fine until I added a few new rows in the table from phpmyadmin and now I keep getting the notice 'undefined variable $query' and

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given

Even though I have not changed my code.

CODE:

<?php
include ('connection.php');
if (isset($_GET ['name'])){
$name = $_GET['forename'];
$name_escaped = mysqli_real_escape_string ($db, $name);

$query = mysqli_query($db, "SELECT * FROM people WHERE name = '$name_escaped'");
if (mysqli_num_rows($query) == null ) echo ('No one with that name in database');{

    //do stuff
}
  }
while ($row = mysqli_fetch_array($query)){
    $name = $row['forename'];
    $email = $row ['emailemailaddress'];
    $phone = $row ['phone'];
    $ext = $row ['extension'];
    $headshot = $row ['headshot'];
    $linkedin = $row ['linkedin'];
    $cv = $row ['cv'];

?>
    <hr style="border-top: dotted 1px;" />
<h2><?php echo strtoupper( $name )?></h2><br><br>
<table style = "font-weight:bold;
        font-family: Century Gothic,CenturyGothic,AppleGothic,sans-serif;">

<tr><td>Email Address:  </td><td><?php echo strtoupper ($email) ?> </td></tr>
<tr><td>Phone Number: &nbsp </td><td><?php echo strtoupper ($phone) ?></td></tr>
<tr><td>Extension: &nbsp </td><td><?php echo strtoupper ($ext) ?></td></tr>
<tr><td>Headshot: &nbsp </td><td><?php echo strtoupper ($headshot) ?></td></tr>
<tr><td>LinkedIn: &nbsp </td><td><?php echo strtoupper ($linkedin) ?></td></tr>
<tr><td>CV: &nbsp </td><td><?php echo strtoupper ($cv) ?></td></tr>

</table>
<br>
<?php }

?>

Does anyone know why this might have happened and what I need to add to fix it? Thanks.

1 Answers1

0

You have $query which is used in while ($row = mysqli_fetch_array($query)){ outside the if(). Move your while() inside your condition.

if (isset($_GET ['name'])){
    $name = $_GET['forename'];
    $name_escaped = mysqli_real_escape_string ($db, $name);

    $query = mysqli_query($db, "SELECT * FROM people WHERE name = '$name_escaped'");
    if (mysqli_num_rows($query) == null ) echo ('No one with that name in database');{

//do stuff
    }
    while ($row = mysqli_fetch_array($query)){
        $name = $row['forename'];
        $email = $row ['emailemailaddress'];
        $phone = $row ['phone'];
        $ext = $row ['extension'];
        $headshot = $row ['headshot'];
        $linkedin = $row ['linkedin'];
        $cv = $row ['cv'];
      }


    ?>
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41