Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create SQL from array

Tags:

sql

php

mysql

I'm trying to create a SQL Query that gets data from my DB depending on what the array includes.

Example:

My array includes 1, 2, 3 then the query should be SELECT * FROM v WHERE category='1' OR category='2' OR category='3'.

Does anyone know a way to achieve this?

Any tips are welcome.

UPDATE:

Using MySQL as DB.

like image 720
Chris Avatar asked Dec 14 '25 15:12

Chris


2 Answers

You can use implode function and IN clause as

$sql="SELECT * FROM v WHERE category IN ('".implode("','", $your_array)."')";
like image 154
Saty Avatar answered Dec 17 '25 06:12

Saty


I would take a look at https://stackoverflow.com/a/14767572/755949, which uses placeholders and PDO to add the parameters to your query. Going with Saty's answer you could risk ending up with a SQL injection.

like image 45
Rob Avatar answered Dec 17 '25 08:12

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!