我正在尝试从数据库中搜索某些数据并显示它。但是,每当我点击“搜索”时,都会显示表格中的所有结果。我能用任何方式只显示用户正在搜索的信息吗? 这是表单的html代码。
<h2> Search </h2>
<form action = "search.php" method = "post" >
Search for: <input type = "text" name ="find" placeholder="Animal Type/Date"><span class="required"</span> in
<select NAME = "field">
<Option VALUE = "Animal Type"> Animal Type</option>
<Option VALUE = "dateseen"> Date Required</option>
</Select>
<input type= "hidden" name = "searching" value ="yes"/>
<input type= "submit" name = "search" value ="Search"/>
</form>
这是我正在使用的PHP代码。
$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,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
//$find = strtoupper($find);
//$find = strip_tags($find);
//$find = trim($find);
$sql=mysqli_query($link, "Select * FROM Locations ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
//}
?>
答案 0 :(得分:1)
为此,您需要首先抓住文本框的find
字段..
$searchKeyword = $_POST['find']; // Sanitize this value first !!
接下来,您需要将其传递给您的查询...更改您的yourcolumn
以适合您的列名称。
$sql=mysqli_query($link, "Select * FROM Locations WHERE `yourcolumn` LIKE '%$searchKeyword%' ");
<强> EDIT :
强>
你可以抓住两个字段并进行检查..
if(!empty($_POST['find']) && !empty($_POST['field']))
{
//do your query like..
$searchKeyword = $_POST['find']; // Sanitize this value first !!
$searchKeyword2 = $_POST['field']; // Sanitize this value first !!
$sql=mysqli_query($link, "Select * FROM Locations WHERE `yourcolumn` LIKE '%$searchKeyword%' AND `yourcolumn2` LIKE '%$searchKeyword2%' ");
}
else
{
echo "The search criteria cannot be empty !";
}