How to remove single quotes in prepare statement?

天涯浪子 提交于 2019-11-28 11:39:17

问题


My query is like this :

$group_id = $session['group_id'];

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

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

When I add : echo $this->db->last_query();die();, the result is like this :

SELECT * FROM notification WHERE group_id IN('1,13,2')

I want remove single quotes in order to the result is like this :

SELECT * FROM notification WHERE group_id IN(1,13,2)

How to remove single quotes in prepare statement?


回答1:


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.




回答2:


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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/38189488/how-to-remove-single-quotes-in-prepare-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!