在数据库中的逗号列表中查找特定值

时间:2013-06-21 17:26:39

标签: php mysql list comma

在我的一个表格中,我有一个列,其中有一个逗号分隔的已购买该项目的用户列表。 IMAGE

如何阅读列表并运行php脚本以查找登录的用户(存储在会话中)是否在该列表中。例如,我怎么能看到登录用户(MTNOfficial)是否在列表中。我认为这是一个带有mysql CONCAT或FIELD_IN_SET的php if语句。

由于

2 个答案:

答案 0 :(得分:2)

使用FIND_IN_SET()查找包含您用户的记录

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

答案 1 :(得分:0)

获取逗号分隔列表,然后尝试使用php函数explode()来获取可以循环的数组。

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!
        }
    }
}