如何让这个mysql查询工作而不会得到空结果?

时间:2011-08-14 22:30:54

标签: php mysql database mybb

我无法从这个mysql查询获得我想要的结果。我认为麻烦在于这行代码:

$ group =“SELECT * from mybb_users where usergroup AND additionalgroups ='$ usergroup'”;

因为我注意到数据库中的additionalgroups列有多个用逗号(,)分隔的值,而用户组只有一个值。这是一个截图:

这是一张图片:http://i.imgur.com/UTbmX.jpg

如果我从代码中删除additionalgroups列并且只检查usergroup列,整个代码工作正常,但这不是我想要的:(以下是整个代码:

// Connect to server and select databse.
mysql_connect("$db_host", "$db_user", "$db_pass")or die("cannot connect to mysql"); 
mysql_select_db("$db_name")or die("cannot select DB");

$id=$_GET['lid'];     // Get lid from URL
$usergroup =$_GET['game'];       // Get the usergroup/game from the URL

// Check to see if the user is a VIP Member and fetch them.
$group="SELECT * from mybb_users where usergroup AND additionalgroups = '$usergroup'";
$group2=mysql_query($group) or die("Could not get users");
while($raw=mysql_fetch_array($group2))
{
// Fetch all UserIDs of the VIP members and match them with the UfID (in the userfields table)
$userid = $raw['uid'];
$group3="SELECT * from mybb_userfields where ufid = '$userid'";
$group4=mysql_query($group3) or die("Could not match userid");
while($raw=mysql_fetch_array($group4))
{
// assigns a lid from the vip members to the variable $lid
$lid = $raw['fid7'];
// Display the hash of the lid if it matches with the lid from the URL
if($lid == '')
{

}
elseif($lid == $id)
{
echo "[key]{$lid};";
}
else
{
}
}

}

2 个答案:

答案 0 :(得分:4)

检查的方法是使用FIND_IN_SET函数。

SELECT * from mybb_users where usergroup AND FIND_IN_SET('$usergroup', additionalgroups) != 0

答案 1 :(得分:1)

我不确定where usergroup AND ... - usergroup是一个数据库字段吗?无论如何,你可以用

来做
$group="SELECT * from mybb_users where usergroup AND FIND_IN_SET('$usergroup', additionalgroups) != 0;

但这还不够。 AFAICS你很容易受到SQL注入攻击。请在正确的位置使用mysql_real_escape(),即将带有用户输入的变量放入SQL查询的任何地方。

相关问题