MySql搜索脚本写入未知错误

时间:2014-03-29 09:19:55

标签: php mysql

这是我在stackoverflow上的第二篇文章,我希望你也能帮我解决这个问题。 当我运行这个脚本时,它会显示“Undefined variable:search_name”.i不知道是什么问题。 希望你能帮忙。 Ty:D。

<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Error" .mysqli_connect_error();
}
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
}

$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." .  ".$ime. "  ".$prezime."<br>";
}





?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>
</form>

2 个答案:

答案 0 :(得分:0)

您需要在提交按钮的isset()内移动查询,否则每次加载页面时都会执行代码,从而导致错误。

if(isset($_POST['go']))
{   
    $search_name = mysqli_real_escape_string($con, $_POST['form_name']);
    $select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
    while($row=mysqli_fetch_array($select_name))
    {
        $ime=$row['name'];
        $prezime=$row['lastname'];
        $id_number=$row['id'];
        echo $id_number." .  ".$ime. "  ".$prezime."<br>";
    }    
}
?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>

答案 1 :(得分:0)

简单地说,只需确保在构建查询之前提交表单,您已经这样做但不是代码的所有部分

if(isset($_POST['go']))
{
    $search_name = mysqli_real_escape_string($con, $_POST['form_name']);
    $select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
    while($row=mysqli_fetch_array($select_name))
    {
        $ime=$row['name'];
        $prezime=$row['lastname'];
        $id_number=$row['id'];
        echo $id_number." .  ".$ime. "  ".$prezime."<br>";
    }
}

这应该解决它。