简体   繁体   中英

selecting the rows in mysql with arrays

In my db, i have a table, Timetable where one field is Subject. It will hold value like this. For example. 1,2,3,4

Now, I need to compare this field with my array named

$mysubs=array('1','3','5');

I have tried this.

select * from Timetable  where Subject IN (".implode(',',$mysubs).");

But if I have only one value in subject field it is working. If it holding something 1,2,3 then it is not working. Is it possible to match using 'LIKE'. Plz help me

Try this query

$sql = "select * from Timetable  where Subject LIKE '".implode(',',$mysubs)."%'";

It may help you.

$values = implode(',',$mysubs);
$query = "select * from Timetable  where Subject IN ($values)";

I use that in some of my projects and it works well

i also thinks it is better to separate query and php operations, at least for a better code readability

Try some thing like this if subject field value is comma separated.

$mysubs = array('1','3','5');
$whereSubClause = '';
for($i=0; $i < count($mysubs); $i++){
   $whereSubClause .= 'FIND_IN_SET($i,subject) OR ';
}
// Remove the last OR
$whereSubClasue = substr($whereSubClause,0,-3); 
// now query
select * from Timetable  where $whereSubClause;

But if it is not comma separated do like this:

$values = implode("','",$mysubs);
"select * from Timetable where subject IN('".$values."');"

This should work:

$mysubs = array(1, 3, 5);
$sql = "SELECT * FROM Timetable WHERE Subject IN (".implode(', ', $mysubs).");";

That should output this:

$sql = "SELECT * FROM Timetable WHERE Subject IN (1, 3, 5);";

It is generally good practice in SQL to capitalize parts of the language like SELECT, INSERT, or UPDATE. Also your array of values you are searching for in $mysubs were strings, though it is better to have them as integers.

You need to save the field with appending and prepending comma.

For example:

,1,2,3,4, OR ,11,12,23,45,

And you need to search for every array element.

$mysubs=array('1','3','5');

select * from Timetable  where Subject LIKE '%,1,%' OR 
Subject LIKE '%,3,%' Subject LIKE '%,5,%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM