从SQL数据库中搜索和显示数据

时间:2014-02-15 14:28:08

标签: php html

我正在尝试在数据库中搜索某些数据并显示它。这是我必须输入搜索条件的html表单代码。

<h2> Search </h2>
<form action = "search.php" method = "post" >
  Search for: <input type = "text" name ="find" /> in
  <select NAME = "field">
    <Option VALUE = "Animal Type"> Animal Type</option>
    <Option VALUE = "latitude"> Latitude</option>
    <Option VALUE = "longitude"> longitude</option>
    <Option VALUE = "dateseen"> Date Required</option>
    <Option VALUE = "timeseen"> Time</option>
  </select>
  <inpput type= "hidden" name = "searching" value ="yes"/>
  <inpput type= "submit" name = "search" value ="Search"/>
</form>

这是我正在使用的php代码。但我仍然在第18/22行和

的错误说明未定义的变量
  

mysql_fetch_array()期望参数1为资源

错误。有什么想法吗?

<?php

if ($searching=="yes")
  {echo "<h2> Results</h2><p>";
  }

if ($find=="")

{echo "<p> Please enter a search iten";
exit;

}

$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$db_selected = mysqli_select_db($link,"Animal_Tracker");

if (!$db_selected)
  {
  die ("Can\'t use test_db : " . mysqli_error());
  }

$find = strtoupper($find);
$find = strip_tags($find);
$find = trim($find);

$sql=mysql_query("Select * FROM Animal_Tracker WHERE upper($field) LIKE '%$find%' ");

while($result = mysql_fetch_array($sql))
{
    echo $result ['Animal Type'];
    echo " ";
echo $result ['latitude'];
echo "<br> ";
echo $result ['longitude'];
echo " <br>";
echo $result ['dateseen'];
echo " <br> ";
echo $result ['timeseen'];
echo "<br> ";
echo "<br> ";
}

1 个答案:

答案 0 :(得分:1)

我设法让您的代码正常运行。你混合mysql和mysqli(我不确定这是不是问题)。

好的做法是检查你的mysql_query是否成功并打印信息。不要忘记使用自己的字段名称(我创建了一个测试数据库)

<?php


$link=mysqli_connect("localhost","root","");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$db_selected = mysqli_select_db( $link, "Animal_Tracker");


 if (!$db_selected){
        die("Couldn't select database $db ".mysqli_error($link));
}


$sql=mysqli_query($link, "Select *  FROM location");

if ($sql == FALSE)
{
  die($sql." Error on query: ".mysqli_error($link)); 
}

while($result = mysqli_fetch_array($sql))
{
    echo $result ['x'];
    echo " ";
    echo "<br> ";
}