Jump to content


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


Dynamic queries with mysqli

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:

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?

Share this post

Link to post
Share on other sites


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.