麻烦使用IN语句与mysql和PHP

时间:2012-02-11 15:44:17

标签: php mysql

我试图根据使用IN语句存储在特定列中的内容从数据库中提取多个用​​户。

用户存储在以“〜”分隔的列中,这就是为什么我使用str_replace删除它所以它只是数字。我尝试使用逗号代替它,但也没用。例如,用户1,2和3将作为“1~2~3”存储在列中。 $ stripSymbol正在工作并正确显示用户,所以我很困惑为什么我不能让sql语句工作。

if($eventBy == $_SESSION['userid']){ 
            if(($requested !=="") OR ($requested !=="~")){
                $stripSymbol = str_replace("~","",$requested); //$requested is the list of users
                echo $stripSymbol; //used for testing, displays the values properly so I know this works
            $userInvites = mysql_query("select userid,username from users where userid IN ($stripSymbol)");
            $userArray = mysql_fetch_array($userInvites);
            $userN = $userArray['username'];
            echo $userN; //testing to see if it's pulling the values properly, nothing is displayed
            }
        }

这是我更新的代码。它只显示列中的最后一个值。

if($eventBy == $_SESSION['userid']){ 
            if(($requested !=="") OR ($requested !=="~")){
                $stripSymbol = explode("~",$requested); 
                $stripSymbol = "'" . implode("', '", $stripSymbol) . "'";
                $userInvites = mysql_query("select userid,username from users where userid IN (".$stripSymbol.")");
                $userArray = mysql_fetch_array($userInvites);
                $userN = $userArray['username'];
                echo $userN; //testing to see if it's pulling the values properly, nothing is displayed
            }
        }

2 个答案:

答案 0 :(得分:0)

您应该更改替换功能:

 $stripSymbol = str_replace("~",",",$requested);

现在用“,”替换“〜”。

添加一些调试信息:

 $userInvites = mysql_query("select userid,username from users where userid IN ($stripSymbol)") or die($q . " " . mysql_error());
 $userArray = mysql_fetch_array($userInvites);

答案 1 :(得分:0)

这是您的代码更正:

if(($requested !=="") OR ($requested !=="~")){
                $stripSymbol = explode("~", $requested); //$requested is the list of users
                $stripSymbol = "'" . implode("', '", $requested) . "'";
                echo $stripSymbol; //used for testing, displays the values properly so I know this works
            $userInvites = mysql_query("select userid,username from users where userid IN ($stripSymbol)");
            $userArray = mysql_fetch_array($userInvites);
            foreach($userArray as $item)
                {
                  $userN = $item['username'];
                  echo $userN . "<br/>"; //testing to see if it's pulling the values properly, nothing is displayed
                }
            }