Parameterized query with several optional search terms

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 10:19:00

You are already protected against sql injection, as you are using the mysqli_stmt_bind_params which will escape properly for you.

Edit. You could switch to some database framework to have a clean and beautiful code.

Otherwise... this is so old spaghetti style... but I love it :D

It's quite easy to expand your code to work with an unknown number of parameters. You should just loop on your parameters and at the same time 1. build your query string with the question mark notation, and add your parameters to an array, which you will be passing to maxdb_stmt_bind_param ( resource $stmt , string $types , array &$var ).

So it would look like this. It assumes at least ONE parameter is there (but it's trivial to avoid this).

$sql = "SELECT * FROM tbl_data WHERE ";
$and = '';
$types = '';
$parameters = array();
foreach($_POST as $k => $v) {
  // check that $k is on your whitelist, if not, skip to the next item
  $sql .= "$and $k = ?";
  $and = " AND ";
  $parameters[] = $v;
  $types .= 's';
}
$stmt_query = mysqli_prepare($db, $sql);
mysqli_stmt_bind_params($stmt_query, $types, $parameters);

I recommend switching to PDO. It's built into PHP like the mysqli extension, but has a cleaner syntax and allows you to pass in your parameter values as an array, which you can easily construct dynamically with as many elements as needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!