sol
sol

Reputation: 440

Array to comma separated strings

This is the code (I'm using Codeigniter):

$sql = 'SELECT * FROM foo WHERE bar IN (?)';

$query = $this->db->query($sql, array($values));

So $values is an array of strings that I want to add in the SQL statement where the "?" is. When I try this I get an "Array to string conversion" error. Is there any way I can add the values of the $values array as comma separated strings into the SQL statement?

Upvotes: 1

Views: 2360

Answers (2)

Shaiful Islam
Shaiful Islam

Reputation: 7134

Why don't you use simple codeigniter way

$this->db->from('foo');
$this->db->where_in('bar',$values);
$query=$this->db->get();

This will produce what you exactly want

Update
If you are strict with your way you need to produce the $sql this way

$sql = 'SELECT * FROM foo';
    if(is_array($values)&&sizeof($values)>0)
    {
        $sql.=' WHERE bar IN (';
        foreach($values as $key=>$value)
        {
            if($key==0)
            {
                $sql.='?';
            }
            else
            {
                $sql.=',?';
            }
        }
        $sql.=')';
    }       

    $query=$this->db->query($sql,$values);

Upvotes: 2

Anand Solanki
Anand Solanki

Reputation: 3425

You should pass string with comma separated in query. for that use implode function of php.

Do like this:

$values = array('bar1', 'bar2', 'bar3');
$string = "'".implode("',", $values)."'";

Then pass string in the query,

$sql = 'SELECT * FROM foo WHERE bar IN ($string)';
$query = $this->db->query($sql);

echo '<pre>'; print_r($query->result_array());

You will data in $query variable.

Let me know for further help if needed.

Upvotes: 2

Related Questions