1

How do I get all the 'name' column corresponding to the supplied ids in a single query ?

Suppose I have a php array like this $ids = [ '1', '3', '7', '24', ... ]; then, is it possible to get the 'name' in the following table WHERE $ids[i]='id' in that table, all in a single query, or do I need to use for loop ?

CREATE TABLE `services` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '',
  `description` varchar(100) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`) USING BTREE
)

I am working with CodeIgniter.

StudentX
  • 2,243
  • 6
  • 35
  • 67
  • 1
    possible duplicate of [PHP/MySQL using an array in WHERE clause](http://stackoverflow.com/questions/907806/php-mysql-using-an-array-in-where-clause) – Criesto Sep 08 '15 at 05:04

3 Answers3

2

You can use where_in for this

$ids = [ '1', '3', '7', '24', ... ];
$this->db->select('name');
$this->db->from('services');
$this->db->where_in('id', $ids);
Saty
  • 22,443
  • 7
  • 33
  • 51
1

you can use IN clause

 SELECT * FROM `services` WHERE ID IN (".implode(',' , $ids).");

In case the dataType is varchar , make sure to add ' accordingly

 SELECT * FROM `services` WHERE ID IN ('".implode('','' , $ids)."');
sanjeev
  • 4,405
  • 2
  • 19
  • 27
0

you can use query bindings too, if the data array repeats :

<?php
    $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";

    $this->db->query($sql, array(3, 'live', 'Rick'));   
?>
Criesto
  • 1,985
  • 4
  • 32
  • 41