【问题标题】:Modifying MySQL Where Statement Based on Array基于数组修改 MySQL Where 语句
【发布时间】:2010-05-22 21:35:09
【问题描述】:

使用这样的数组:

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

我想创建一个 MySQL 查询,它使用数组的值来形成它的 WHERE 子句,例如:

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

如何生成此查询字符串以与 MySQL 一起使用?

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      请不要使用嵌入数据构建 SQL 语句。看这里:http://bobby-tables.com/php.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多