开发者

Modifying MySQL Where Statement Based on Array

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?


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" );


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜