搜索功能中未定义的索引

时间:2014-05-29 18:33:26

标签: php

<?php

//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_POST['name']);

//check whether the name parsed is empty
if($searchTerm == "")
{
    echo "Enter name you are searching for.";
    exit();
}

//database connection info
$host = "localhost"; //server
$db = "name"; //database name
$user = "root"; //dabases user name
$pwd = ""; //password

//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);

//MYSQL search statement
$query = "SELECT * FROM user WHERE name LIKE '%$searchTerm%'";

$results = mysqli_query($link, $query);

/* check whethere there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
    $output = "";
    while($row = mysqli_fetch_array($results))
    {
        $output .= "Name: " . $row['name'] . "<br />";
        $output .= "Matric: " . $row['matric_no'] . "<br />";
        $output .= "Email Address: " . $row['email_add'] . "<br /><br />";
    }
    echo $output;
}
else
    echo "There was no matching record for the name " . $searchTerm;
?>

我的代码出了什么问题?如何解决这个问题?有人可以帮助我吗? 这是错误

  

注意:未定义的索引:第16行的C:\ xampp \ htdocs \ xampp \ foundation \ testing.php中的名称

2 个答案:

答案 0 :(得分:3)

确保在尝试使用变量之前设置变量。

if ( isset($_POST['name']) ) {
    $searchTerm = trim($_POST['name']);
    // The rest of your code... 
}

答案 1 :(得分:0)

当您尝试存储表单提交的值(如POST或GET)时,检查值是否真的发送确实是一个好习惯。您必须使用isset来检查相同内容。

POST类型示例:

if(isset($_POST['name']))
{
  $searchTerm=trim($_POST['name']);
}
else
{
  // The user have not filled the <input name='name'> do something for empty
}

GET类型示例:

if(isset($_GET['name']))
{
  $searchTerm=trim($_GET['name']);
}
相关问题