0

I am looking to be able to search a SQL database using a form and output the finds on the screen.

This is my code:

$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();

It selects and outputs the information. The thing is I need people to be able to leave a field blank the search form however this causes all data to be displayed. If they type in the county and leave everything else blank I want it to pull only that county records.

4

3 回答 3

0

我建议检查 post 值是否已设置并将 where 条件存储在数组中,然后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 注入攻击的保护,您需要清理您的输入。

于 2012-11-14T16:59:16.550 回答
0

您可以打破where子句条件,例如:

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

并注入$where查询。

于 2012-11-14T15:54:07.817 回答
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']);
// ...
于 2012-11-14T15:54:17.890 回答