2014-02-15 140 views
-1

我正試圖搜索數據庫中的一些數據並將其顯示出來。這是我必須輸入搜索條件的html表單代碼。從SQL數據庫中搜索並顯示數據

<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

您使用一個變量叫'$ field'在您的SQL查詢,但你不隨地定義它。 – David

+2

你正在做一個mysqli連接並執行mysql_ *函數.. –

回答

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> "; 
} 
+0

謝謝你這有幫助,但你能告訴我如何使用代碼的前六行。我如何定義$ find和$ search,以便它也可以訪問HTML代碼?否則,即使我沒有輸入任何信息,它也會顯示數據庫中的所有數據。 – user3293736

+1

當然,看看這裏http://stackoverflow.com/questions/17139501/using-post-to-get-select-option-value - 從-HTML。與其合作是一個非常普遍的問題。 – VonSchnauzer