使用PDO搜索

时间:2014-04-10 20:37:13

标签: php mysql search pdo

所以我尝试使用PDO执行搜索。我有这个搜索设置:

echo "<form action = 'user.php?search=yes' method = 'post' id='searchform'>
<a href='user.php?newuser=yes'>Add New User</a> || Search By
<select name = 'paramet' form = 'searchform'>
<option value = 'userID'>User ID</option>
<option value = 'firstname'>First Name</option>
<option value = 'lastname'>Last Name</option>
<option value = 'email'>E-Mail</option>
<option value = 'mobileno'>Mobile Number</option>
<option value = 'homeno'>Home Number</option>
</select>
<select name = 'howso' form = 'searchform'>
<option value = 'contains'>which contains</option>
<option value = 'equalto'>which is equal to</option>
</select>
<input type = 'text' name='criteria' required>
<input type = 'submit' value='Search'>
</form>

然后处理查询:

{
$param = $_POST['paramet'];
$how = $_POST['howso'];
$crite = $_POST['criteria'];
if($how == 'contains')
{
$query = $hsdbc->prepare("SELECT * FROM user WHERE :param LIKE :crite");
$query->bindParam(':param', $param);
$query->bindValue(':crite', '%' . $crite . '%');
$query->execute();
}
else{
$query = $hsdbc->prepare("SELECT * FROM user WHERE :param = :crite");
$query->bindParam(':param', $param);
$query->bindParam(':crite', $crite);
$query->execute();
}

我无法在正确的结果附近找到合适的地方。有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

您无法绑定列名称。您可以做的最好的事情是将名称添加到白名单数组或其他内容并手动插入。

   if(in_array($param, $good_params_array)) {
         $query = $hsdbc->prepare("SELECT * FROM user WHERE $param LIKE :crite");
         $query->bindValue(':crite', '%' . $crite . '%');
         $query->execute();
   }

我已经看到人们在数据库中查询表描述以获取列以查看是否列出了列名,但这需要额外的数据库请求。此外,您可能希望限制他们可以搜索的字段