using implode for array inside mysql where in clause

后端 未结 2 1548
醉话见心
醉话见心 2021-01-23 04:41

im trying to use array for mysql where in clause

$result= $myDB->query(\"SELECT sum(total) as total FROM \".$myDB->prefix(\"mydata\").\" WHERE categoryname         


        
相关标签:
2条回答
  • 2021-01-23 05:39

    the naive solution will be:

    $array = ['Cat1', 'Cat2', 'Cat3'];
    echo "'" . implode("','", $array) . "'";
    

    but it could introduce sql injection, so you need properly escape data in array first

    sample one-line with escaping:

    echo "'" . implode("','", array_map('mysql_escape_string', $array)) . "'";
    

    note: mysql_* functions are deprecated, you need to use mysqli_* which require connection link

    0 讨论(0)
  • 2021-01-23 05:42

    I did something similar a while ago using array_map, hope it helps:

    $args = array_map(function($a) {
        return sprintf("'%s'", $a);
    }, $args);
    
    $args = join(",", $args);
    

    The above code will iterate over the array and modifies every single element to surround it with ''. Finally, I join the array with ,.

    0 讨论(0)
提交回复
热议问题