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?
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.
The FIND_IN_SET() function returns the position of a string within a list of strings.
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.
$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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With