出于安全原因,我肯定会首先列出可以在查询中使用的可用键及其数据类型。
$keys = array(
'category' => PDO::PARAM_INT,
'price' => PDO::PARAM_INT,
'etc' => PDO::PARAM_STR
);
// all the available keys for the query and their types
$queryStr = "SELECT * FROM `some_table` WHERE `yourCond`='someVal'";
// initial query you have
$userVals = array();
foreach ($_GET as $key => $value) {
$k = strtolower($key);
if (!in_array($k,array_keys($keys)) || empty($value))
// if the key is not listed in the keys array
// or the value is empty we skip it
continue;
$queryStr .= " AND `$k` = :{$k} ";
// modify query
$userVals[$k] = $value;
// and add the key-value pair into user values array
}
$db = new PDO('mysql:host=someHost;dbname=someDB','someUsername','somePassword');
// create DB connection
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// enable error reporting
$stmt = $db->prepare($queryStr);
// prepare query string
foreach ($userVals as $k => $v) {
$stmt->bindParam(":{$k}",$v,$keys[$k]);
// bind each parameter with the right datatype
}
$stmt->execute();
// and execute the query