php - How to parametrize SQL query with multiple WHERE conditions (prepared statement)? -


i have multiple conditions in clause inputted user (call them filters). processing them way (don't worry isn't deployed):

//$by_nickname etc. filters $_get  $conditions = array();  if($by_nickname !="") {     $conditions[] = " players.lastname ('%" . $by_nickname . "%')"; }  if($by_steamid !="") {     $conditions[] = " ids.uniqueid = '$by_steamid'"; }  if($by_ip !="") {     $conditions[] = " players.lastaddress = '$by_ip'"; }  if($by_msg !="") {     $conditions[] = " chat.message ('%" . $by_msg . "%')"; }  if (count($conditions) > 0) {     $where = implode(' , ', $conditions);     $query = "select ... " . $where; } else {     $query = "select ... "; } 

instead of use

$conditions[] = " ids.uniqueid = ?"; 

and on. obtain $where, ? instead of filter values.

query should prepared

$stmt = $mysqli->prepare("select ... $where"); 

and parametrized this

$stmt->bind_param('ss', $by_nickname, $by_steamid); 

but how parametrize query if filters empty? simply, don't know bind_param() method arguments in advance.

i have solved problem using pdo has named parameters. here solution, hope helps somebody.

$by_nickname = $_get['nickname']; $by_steamid = $_get['steamid']; // integer $by_serverid = $_get['serverid'];  $pdo = new pdo("mysql:host=host;port=port;dbname=db;charset=utf8", "user", "password");  $conditions = array(); $parameters = array(); $where = "";  if($by_nickname !="") {     $conditions[] = " players.nickname :nickname";     $parameters[":nickname"] = "%$by_nickname%"; }  if($by_steamid !="") {     $conditions[] = " ids.steamid = :steamid";     $parameters[":steamid"] = $by_steamid; }  if($by_serverid !="") {     $conditions[] = " servers.serverid = :serverid";     // beware of correct parameter type!     $parameters[":serverid"] = intval($by_serverid); }  if (count($conditions) > 0) {     $where = implode(' , ', $conditions); }  // check if $where empty string or not $query = "select ... " . ($where != "" ? " $where" : "");  try {     if (empty($parameters))     {         $result = $pdo->query($query);     }     else     {         $statement = $pdo->prepare($query);         $statement->execute($parameters);         if (!$statement) throw new exception("query execution error.");         $result = $statement->fetchall();     } } catch(exception $ex) {     echo $ex->getmessage(); }  foreach($result $row) {   // example   echo row["<column name>"]; } 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -