简体   繁体   English

如何从Mysql中选择逗号分隔变量

[英]How to SELECT Comma Separated variable From Mysql

I Have a MySql Database Structure and values samples as shown below: 我有一个MySql数据库结构和值示例如下所示:

sno     firstname      status
1        John            Active
2        Kelly           Inactive
3        Harri           Passive
4        Kris            Dormant

Now that I need to execute a Sql query from a PHP page, and the Status Values are from multiple checkbox which I have assigned as an array. 现在我需要从PHP页面执行Sql查询,并且状态值来自多个复选框,我已将其指定为数组。

I have used Implode function for this array: 我已经为这个数组使用了Implode函数:

$status = $_POST['status'];    
$mstat= implode (',', $status);
$query="SELECT * FROM USER WHERE status IN '$mstat'";
$result=mysql_query($query);

while ($members = mysql_fetch_assoc($result))
        { 
        $fname= $members['firstname'];
        echo $fname;
        echo '</br>';
        }

The problem is that I'm not getting any results. 问题是我没有得到任何结果。 What could be the problem. 可能是什么问题呢。 Or If anyone could suggest/Advice for an alternative. 或者,如果有人可以建议/建议替代方案。

When I echo $mstat; 当我echo $mstat; I get Active,Passive,Dormant (That is based on my checkbox selection) 我得到Active,Passive,Dormant (这是基于我的复选框选择)

status are strings. status是字符串。 You need to wrap them with quotes . 你需要用quotes包装它们。 And IN needs () to wrap the string values. 并且IN needs ()包装字符串值。 Try - 试试 -

$mstat= "'" . implode ("','", $status) . "'";
$query="SELECT * FROM USER WHERE status IN ($mstat)";

Assuming $status contains some or all of those values showed in database in array format. 假设$status包含数据库中以数组格式显示的部分或全部值。

Here is 100% working answer 这是100%的工作答案

$mstat= implode ("','", $status);
$query="SELECT * FROM USER WHERE status IN ('$mstat')";

IN works like this IN ('Active','Passive','Dormat') so we have to add '' in all values which is done in implode function. IN就像这样的IN('Active','Passive','Dormat')所以我们必须在implode函数中添加所有值中的''。

Change this line to: 将此行更改为:

$query="SELECT * FROM USER WHERE status IN ('$mstat')";

The Argument must in () 论证必须在()

!!! EACH word must in ' ' like: $query="SELECT * FROM USER WHERE status IN ('Active','Inactive')" 每个单词必须在''like:$ query =“SELECT * FROM USER WHERE status IN('Active','Inactive')”

You can change it like: 你可以改变它:

if ($mstat) $query .= ' ({$db->quote($status}) ';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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