I'm trying to find a better way to search arrays stored in my mySql database to decide if I want to return values from that row. Currently I am parsing the entire array, and if it includes what I want, I go on to do whatever it is I want to do, and if it does not, I move on to the next row. It's super slow.
I have array stored in a column, which we'll call category. Ex: 1,zzz31zzz,31,4,5
I want to search that column, and if it contains "31", go on to manipulate my data.
So I access my db like this:
$sql = "SELECT * FROM db WHERE arg=1 AND category != ''";
$sqlresult = mysql_query($sql);
while($row = mysql_fetch_array($sqlresult))
{
$vals = explode(',', $row['category']);
foreach($vals as $val)
{
if($val == 31)
{
//do something
}
else
{
//dont
}
}
}
I feel like there is an obvious answer that I'm just not thinking about. Can anyone suggest a better alternative? I'm going to be processing thousands of arrays this way, and 3 takes nearly half a second as is. I would be hesitant to use wildcards in my search, as it is possible that I could have data such as "1311" etc.. I pretty much need to search for a specific variable.
-- Thanks everyone for the immediate responses. I will be able to test them here in a couple hours. I appreciate the suggestions.
Implying your delimiter is ,
WHERE `category` REGEXP ',?[SEARCHED-VALUE],?';
What about this :
$sql = "SELECT * FROM db WHERE arg=1 AND (category LIKE '%,31,%' OR category = 31 OR category LIKE '31,%' OR category LIKE '%,31'";
You won't match '1311', etc if I got what you want.
Otherwise, give a look at the REGEXP SQL function
check this :->
while($row = mysql_fetch_array($sqlresult))
{
$vals = explode(',', $row['category']);
IF(in_array('31',$vals)
{
//do something
}
else
{
//dont
}
}
OR
you can use FIND_IN_SET() with mysql queries