Find specific value in comma list in database

大兔子大兔子 提交于 2019-12-04 05:51:55

问题


In one of my tables, i have a column where it has a comma seperated list of users that have bought that item. IMAGE

How can i read the list and run a php script to find if the user that is logged in (that is stored in the Session) is in that list. For example, how could i see if the logged on user (MTNOfficial) is in the list. I think its a php if statement with a mysql CONCAT or FIELD_IN_SET or something.

Thanks


回答1:


Use FIND_IN_SET() to find the records that contain your user

select *
from your_table
where find_in_set('MTNOfficial', usersBought) > 0



回答2:


Get the comma separated list, then try the php function explode() to get an array that you can loop over.

http://php.net/manual/en/function.explode.php

$target = "MTNOfficial";
$query = "select usersBought from table_name";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $users = explode("," $row['usersBought']);
    // may want to trim() here
    for ($i = 0; $i < count($users); i++) {
        if ($users[i] == $target) {
            //we found him!
        }
    }
}


来源:https://stackoverflow.com/questions/17241021/find-specific-value-in-comma-list-in-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!