2012-11-14 112 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注入攻击,您需要清理您的输入。