How to remove single quotes in prepare statement?

后端 未结 5 2058
余生分开走
余生分开走 2020-12-22 11:16

My query is like this :

$group_id = $session[\'group_id\'];

$sql = \"SELECT *
        FROM notification 
        WHERE group_id IN(?)\";

$result = $this-&g         


        
相关标签:
5条回答
  • 2020-12-22 11:44

    Changing %s placeholder to %1s remove Automattic single quote in prepare statement.

    Example:

    global $wpdb
    $sql = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}posts WHERE post_status='wc-completed' AND ID IN(%1s)", '1,2,3' );
    

    Reference links: Thanks

    0 讨论(0)
  • 2020-12-22 11:50

    You can this as below:

    $session['group_id'] is probably a string. so you can convert that string into an array.

    $group_id = explode(",", $session['group_id']);
    

    Now $group_id is already an array. So, in below statement replace array($group_id) with just '$group_id':

    $result = $this->db->query($sql, array($group_id))->result_array();
    

    so whole code will be like:

    $group_id = explode(",", $session['group_id']);
    
    $sql = "SELECT *
            FROM notification 
            WHERE group_id IN(?)";
    
    $result = $this->db->query($sql, array($group_id))->result_array();
    
    0 讨论(0)
  • 2020-12-22 11:59

    All you have to do is make an array of group ids. Try as following

    $group_id = explode(',',$session['group_id']);
    $this->db->select('*');
    $this->db->where_in('group_id',$group_id);
    $this->db->get('notification');
    

    it will work

    0 讨论(0)
  • 2020-12-22 12:00

    I prefer you can use where_in command as below:-

    $this->db->select('*');
    $this->db->where_in('group_id',$group_id);
    $this->db->get('notification');
    
    0 讨论(0)
  • 2020-12-22 12:03

    You either need to dynamically add in as many ? as you have values in the array...

    Or stop using a prepared query and do something like the following:

    $group_id = $session['group_id'];
    
    $sql = "SELECT *
        FROM notification 
        WHERE group_id IN (".implode($group_id,",").")";
    

    If the data hasn't come from a user you don't necessarily need to use a prepared query to make sure the data is safe. But if necessary you could do an is_numeric() check before the query to see if the data is valid.

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