Binding an unknown number of parameters using mysqli

后端 未结 1 1189
广开言路
广开言路 2021-01-21 13:46

I\'m trying to make a search in a table, something like this: http://www.phpjabbers.com/free-scripts/mysql-search-table/search.php

I figured out that I could just concat

相关标签:
1条回答
  • 2021-01-21 14:26

    A bit sloppy, but gets the job done.

    function refValues($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }
    
    $params = array();
    
    $query = "SELECT * FROM table WHERE status = 1";
    
    // Iterate over your paramters from $_GET
    foreach ($_GET as $k => $v) 
    { 
      if(!empty($v)
      {
        $query .= " AND $k = ?";
        $params[$k] = helper::sanitize($v);
      }
    }
    // After you get through all your params...
    
    $stmt = $mysqli->prepare($query);
    
    // Bind em.
    call_user_func_array(array($stmt, 'bind_param'), refValues($params));
    

    That should do it, though I've never bound with mysqli before. Let me know how that works.

    0 讨论(0)
提交回复
热议问题