0

I have an array of values that I want to check using the mysql IN() function but how do I use it with codeigniter?

This is what I'm currently doing which obviously doesn't work.

$p = array('page1', 'page2', 'page3','page4', 'page5');
$pages = implode(",", $p);

$sql = "select page from pages where domains_id = ? and page in(?) and is_deleted=0";
$fields = array($domains_id, $pages);

$this->db->query($sql, $fields)

the output of the pages variable comes out to  page1,page2,page3,... but the in function needs them seperated like this:
'page1','page2','page3'....
0

3 Answers 3

1
<?php
function addQuotes($string)
{
    return "'{$string}'";
}
$p = array('page1', 'page2', 'page3','page4', 'page5');
$p2 = array_map("addQuotes", $p);

print_r($p2);

See it in action

You can then use your implode() normally.

Sign up to request clarification or add additional context in comments.

Comments

0

Start with the outer quotes the implode with ','

$pages = sprintf( "'%s'", implode( "','", $p ) );

3 Comments

Won't this leave the application vulnerable to SQL injection?
@MikeB - depends where $p comes from
Which means you've got to trace it instead of just doing it the safe way and being sure it's correct. Seems like a trap.
0

Try this:

$p = array('page1', 'page2', 'page3','page4', 'page5');
$this->db->select('page');
$this->db->from('pages');
$this->db->where('domains_id', $domains_id);
$this->db->where_in('page', $p);
//Note where_in function expects 2nd parameter as array
$this->db->where('is_deleted', '0');

$query = $this->db->get();

For more details: http://ellislab.com/codeigniter/user-guide/database/active_record.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.