1

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 Answers 2

4

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" );
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.