Jump to content

Dynamic queries with mysqli


Soabirw

Recommended Posts

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:

[code]
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
    $where
";
[/code]

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

Then run:
$stmt->bind_param('s',$criteria['username']);

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?
Link to comment
https://forums.phpfreaks.com/topic/10150-dynamic-queries-with-mysqli/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.