Home » Php » php – Pass array to where in Codeigniter Active Record

php – Pass array to where in Codeigniter Active Record

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a table in my database with adminId and clientId

There might be 20 records with the adminId of the logged in user and I’m trying to pull a list of clients.

I am wondering if there is a way i can say something like:

$this->db->where('id', '20 || 15 || 22 || 46 || 86');

I’m trying to do this with dynamic data (you never know how many clients Id’s you’ll need to pull). Any ideas?

How to&Answers:
$this->db->where_in('id', ['20','15','22','42','86']);

Reference: where_in

Answer:

Use where_in()

$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );

Answer:

From the Active Record docs:

$this->db->where_in();

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

Answer:

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,

$this->db->where_in()
ex :  $this->db->where_in('id', array('1','2','3'));

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate

$this->db->or_where_in()
ex :  $this->db->where_in('id', array('1','2','3'));