Issue when trying to use IN() in wpdb

后端 未结 4 1173
旧时难觅i
旧时难觅i 2020-11-28 13:52

i have this:

$villes = \'\"paris\",\"fes\",\"rabat\"\';
$sql    = \'SELECT distinct telecopie FROM `comptage_fax` WHERE `ville` IN(%s)\';
$query  = $wpdb->         


        
相关标签:
4条回答
  • 2020-11-28 14:06

    WordPress already has a function for this purpose, see esc_sql(). Here is the definition of this function:

    Escapes data for use in a MySQL query. Usually you should prepare queries using wpdb::prepare(). Sometimes, spot-escaping is required or useful. One example is preparing an array for use in an IN clause.

    You can use it like this:

    $villes = ["paris", "fes", "rabat"];
    $villes = array_map(function($v) {
        return "'" . esc_sql($v) . "'";
    }, $villes);
    $villes = implode(',', $villes);
    $query = "SELECT distinct telecopie FROM `comptage_fax` WHERE `ville` IN (" . $villes . ")"
    
    0 讨论(0)
  • 2020-11-28 14:10

    The prepare function also takes an array as the second parameter.

    You can try converting $villes like this:

    Current

    <?php
    $villes = '"paris","fes","rabat"';
    ?
    

    Change it to

    <?php
    $villes = array("paris","fes","rabat");
    ?>
    

    Now, try passing $villes to the prepare func and see if it works. Hope it helps.

    0 讨论(0)
  • 2020-11-28 14:17

    FUNCTION:

    function escape_array($arr){
        global $wpdb;
        $escaped = array();
        foreach($arr as $k => $v){
            if(is_numeric($v))
                $escaped[] = $wpdb->prepare('%d', $v);
            else
                $escaped[] = $wpdb->prepare('%s', $v);
        }
        return implode(',', $escaped);
    }
    

    USAGE:

    $arr = array('foo', 'bar', 1, 2, 'foo"bar', "bar'foo");
    
    $query = "SELECT values
    FROM table
    WHERE column NOT IN (" . escape_array($arr) . ")";
    
    echo $query;
    

    RESULT:

    SELECT values
    FROM table
    WHERE column NOT IN ('foo','bar',1,2,'foo\"bar','bar\'foo')
    

    May or may not be more efficient, however it is reusable.

    0 讨论(0)
  • 2020-11-28 14:30

    Try this code (FIXED):

    // Create an array of the values to use in the list
    $villes = array("paris", "fes", "rabat");    
    
    // Generate the SQL statement.
    // The number of %s items is based on the length of the $villes array
    $sql = "
      SELECT DISTINCT telecopie
      FROM `comptage_fax`
      WHERE `ville` IN(".implode(', ', array_fill(0, count($villes), '%s')).")
    ";
    
    // Call $wpdb->prepare passing the values of the array as separate arguments
    $query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $villes));
    
    echo $query;
    
    • implode()
    • array_fill()
    • call_user_func_array()
    • array_merge()
    0 讨论(0)
提交回复
热议问题