2012-11-14 133 views
0

我期望能夠使用表單搜索SQL數據庫並在屏幕上輸出查找結果。打印SQL查詢結果PHP

這是我的代碼:

$query = "SELECT * FROM documents WHERE DocumentName = '%".$DocumentName."%'AND county = '".$county."' OR acreage = '".$acreage."' AND grantor = '".$grantor."' OR grantee = '".$grantee."' ORDER by 'DocumentName'" ; 

$result=$db->query($query); 
$num_results=$result->num_rows; 
echo "<p>Number of documents found: ".$num_results."</p>"; 
for($i=0; $i <$num_results; $i++){ 
$row=$result->fetch_assoc(); 
echo"<p>".($i+1).".County: "; 
echo htmlspecialchars(stripslashes($row['county'])); 
echo "<br />Acreage: "; 
echo stripslashes($row['acreage']); 
echo "<br />Grantor: "; 
echo stripslashes($row['grantor']); 
echo "<br />grantee: "; 
echo stripslashes($row['grantee']); 
echo "<br />Lessor: "; 
echo stripslashes($row['DocumentName']); 
echo "<br />PDF: "; 
echo stripslashes ("<a href=".$row['PDF'].">" .$row['PDF'] . "</a><br>"); 
echo "</p>"; 
} 

$result->free(); 
$db->close(); 

它選擇並輸出該信息。事情是我需要人們能夠將一個字段留空搜索表單,但是這會導致顯示所有數據。如果他們在縣裏輸入並且留下一切空白,我希望它只提取縣裏的記錄。

+1

'DocumentName ='%「。$ DocumentName。」%''=>'DocumentName ='「。$ DocumentName。」''' –

回答

0

可以打破where條款的條件,如:

$where = ''; 
$where .= empty(county) ? '' : "AND county='$county' "; 
... 

並在查詢注入$where

0

嘗試是這樣的(以顯示數據僅當關聯的表單字段被髮送,而不是空的)

if(isset($_POST['country']) && strlen($_POST['country'])>0) echo ($i+1).".County: ". htmlspecialchars(stripslashes($row['county'])); 
if(isset($_POST['acreage']) && strlen($_POST['acreage'])>0) echo "<br />Acreage: ". stripslashes($row['acreage']); 
// ... 
0

我建議檢查值設置在柱和存儲,其中在陣列中的條件,然後使用implode在您的查詢中使用一個字符串。

if(isset($_POST['country']) && strlen($_POST['country'])) { 
    $where[] = "country = '$country'"; 
} 
if(isset($_POST['acreage']) && strlen($_POST['country'])) { 
    $where[] = "acreage = '$acreage'"; 
} 
.... 
$where = isset($where) ? ' WHERE '.implode(' AND ',$where) : ''; 
$query = 'SELECT * FROM documents'.$where; 

還值得注意的是,您沒有防範SQL注入攻擊,您需要清理您的輸入。