Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql where id is in array [duplicate]

I have a string of ids like 1,2,3,4,5 and I want to be able to list all rows in mysql where the ID is contained in that list.

I assumed the easiest way would be to turn the string into an array and then match in ($array) but it doesn't work for me - no errors etc but it returns no rows:

$string="1,2,3,4,5"; $array=array_map('intval', explode(',', $string)); $query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')"); 

If I do a var_dump of $array I get:

array(5) {      [0]=> int(1)      [1]=> int(2)      [2]=> int(3)      [3]=> int(4)      [4]=> int(5)  } 

Any idea where I am screwing up?

like image 969
bhttoan Avatar asked Nov 25 '13 20:11

bhttoan


People also ask

How do I query an array in MySQL?

An array is type of data structure defined in MySQL. MySQL provides WHERE IN clause that is useful to apply in the array variable to produce the query set from specific table in the database. WHERE IN clause supports to fetch data values from an array of parameters provided in the query statement in MySQL.

What is Find_in_set in MySQL?

The FIND_IN_SET() function returns the position of a string within a list of strings.

How do I find unique rows in MySQL?

You can use the DISTINCT command along with the SELECT statement to find out unique records available in a table. mysql> SELECT DISTINCT last_name, first_name -> FROM person_tbl -> ORDER BY last_name; An alternative to the DISTINCT command is to add a GROUP BY clause that names the columns you are selecting.


1 Answers

$string="1,2,3,4,5"; $array=array_map('intval', explode(',', $string)); $array = implode("','",$array); $query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')"); 

NB: the syntax is:

SELECT * FROM table WHERE column IN('value1','value2','value3')

like image 88
Crayon Violent Avatar answered Sep 28 '22 06:09

Crayon Violent