Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

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" );
share|improve this answer
    
It's perfect! Thanks so much! –  Ryan May 22 '10 at 21:44
2  
Lest we forget Little Bobby Tables: xkcd.com/327 –  OMG Ponies May 22 '10 at 21:50
1  
Added a link below to bobby-tables.com/php.html –  Andy Lester Jun 3 '10 at 16:30

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.