-1

I am trying to debug a form that gives me errors when the form is not submitted, when it is submitted the errors go away and the results are returned. This is a simplified version of my form that throws up the same errors. Can anyone tell me what I am doing wrong? Thanks...

The errors:

Notice: Undefined variable: result in simple_search.php on line 23

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,null given in
simple_search.php on line 23

simple_search.php

<?php
error_reporting(E_ALL);
include_once "db_conx.php";

//Process Form
if(isset($_GET['searchquery']) && $_GET['searchquery'] != ""){
$searchquery = preg_replace('#[^a-z 0-9?!]#i', '',$_GET['searchquery']);

//Query
$query = "SELECT * FROM mytable WHERE firstname LIKE '%$searchquery%'";
$result = mysqli_query($db_conx,$query);
}
//Form here
echo "<h1>My Form</h1>";
echo " <form action =\"simple_search.php\" name=\"searchForm\" method=\"GET\">

<input type=\"text\" name=\"searchquery\">
<input type=\"submit\" value=\"Submit\">
</form>\n";

//Query database

while ($row = mysqli_fetch_array($result))
{
$firstname= $row['firstname'];

echo $firstname;
echo "<br>";
}
?>
JulianJ
  • 1,259
  • 3
  • 22
  • 52
  • Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Epodax Nov 25 '15 at 14:01

1 Answers1

2

You need to close your if(isset($_GET['searchquery']) && $_GET['searchquery'] != ""){ at the end of your page. When you come to page without submit the form

while condition runs every time

rewite your code as

<?php

error_reporting(E_ALL);
include_once "db_conx.php";
echo "<h1>My Form</h1>";
echo " <form action =\"simple_search.php\" name=\"searchForm\" method=\"GET\">

<input type=\"text\" name=\"searchquery\">
<input type=\"submit\" value=\"Submit\">
</form>\n";

//Process Form
if (isset($_GET['searchquery']) && $_GET['searchquery'] != "") {
    $searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_GET['searchquery']);

//Query
    $query = "SELECT * FROM mytable WHERE firstname LIKE '%$searchquery%'";
    $result = mysqli_query($db_conx, $query);
//Form here
//Query database

    while ($row = mysqli_fetch_array($result)) {
        $firstname = $row['firstname'];

        echo $firstname;
        echo "<br>";
    }
}// isset condition end here
?>
Saty
  • 22,443
  • 7
  • 33
  • 51