Jump to content


Dynamic queries with mysqli

  • Please log in to reply
No replies to this topic

#1 Soabirw

  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 21 May 2006 - 11:38 PM

Moving towards mysqli so I can use prepared statements. So far I am liking it, but now and then I need my queries to be a bit more dynamic. For example, I want to pass an array of fields and build my own where clause. Problem I'm having is I can't figure out how to dynamically bind params. Here is my old code as an example:

if(!empty($criteria['username'])) {
    $where_list[] = " username = '".mysql_real_escape_string($criteria['username'])."'";

if(!empty($where_list)) {
    $where = "WHERE ";
    $where .= implode(" AND ",$where_list);

$sql_list = "SELECT id, CONCAT(last_name, ', ', first_name, '(', username, ')') AS label
    FROM users

That works just fine, but with mysqli prepare I need to run a query more like:
SELECT id FROM users WHERE username = ?

Then run:

As I mentioned earlier the function allows you to pass in an array. Which could look something like:
User::listUsers(array('username' => 'jjohnson', 'first_name' => 'joe', 'last_name' => 'johnson'));

My old code handles it just fine, but I can't figure out how to make the bind_param work this way. I know others have used prepared statements flexible enough, any suggestions?

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users