tags:

views:

30

answers:

2

Using an array like this:

$data = array
     (
       'host' => 1,
       'country' => 'fr',
     )

I would like to create a MySQL query that uses the values of the array to form its WHERE clause like:

SELECT *
FROM table
WHERE host = 1 and country = 'fr'

How can I generate this query string to use with MySQL?

+2  A: 

Try this

$where = '';

foreach( $data as $k => $v ) {
    if( !empty( $where ) )
        $where .= ' AND ';

    $where .= sprintf( "`%s` = '%s'", mysql_real_escape_string( $k ), mysql_real_escape_string( $v ) );
}

mysql_query( "SELECT * FROM `table` WHERE $where" );
Kerry
It's perfect! Thanks so much!
Ryan
Lest we forget Little Bobby Tables: http://xkcd.com/327/
OMG Ponies
Added a link below to http://bobby-tables.com/php.html
Andy Lester
A: 

Please please please don't build SQL statements with embedded data. Look here: http://bobby-tables.com/php.html

Andy Lester