为什么这个表格会给我错误?

时间:2015-11-25 13:58:21

标签: php mysql forms while-loop

我正在尝试调试一个表单,该表单在未提交表单时给出错误,在提交表单时错误消失并返回结果。这是我的表单的简化版本,它会引发相同的错误。谁能告诉我我做错了什么?感谢...

错误:

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>";
}
?>

1 个答案:

答案 0 :(得分:2)

您需要关闭页面末尾的if(isset($_GET['searchquery']) && $_GET['searchquery'] != ""){。当你来到页面而不提交表格

  

虽然条件每次都会运行

将您的代码重写为

<?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
?>