我正在尝试创建属于某个组的用户表,但我似乎无法让它工作。该列表存储在一列中,以便每个用户 ID # 由“~”分隔。例如,如果用户 1,2 和 3 正在参加,该列将显示“1~2~3”。这就是我使用 explode 的目的。
我收到以下错误“警告:mysql_fetch_array() 期望参数 1 为资源, bool 值给出”这是针对定义 $friend 的行。
$attendingUsers = mysql_query("Select acceptedInvites from events where eventID = ".$_GET['eventID']." ");
while($friend = mysql_fetch_array($attendingUsers)){
$users = $friend['acceptedInvites'];
$userExplode = explode("~",$users);
for($i=0; $i<count($userExplode);$i++){
echo $userExplode[$i]; //displays the userid number properly so I know this is working
$friendInfo = mysql_query("select (userid,username) from users where userid = '". $userExplode[$i]."' ");;
$friend = mysql_fetch_array($friendInfo);
echo '<table><tr><td><a href="profile.php?userid=' . $friend['userid'] . '">' . $friend['username'] . '</a></td>';
}
}
我开始认为这与 $friendInfo 有关,因为当我回显它时没有显示任何内容(通常会显示数组)。
最佳答案
这里有一些问题。您遇到的主要问题是查询中没有错误处理和语法错误。选择列表列周围不应有括号:
$friendInfo = mysql_query("select userid, username from users where userid = '". $userExplode[$i]."' ");
//-------------------------------^^^^^^^^^^^^^^^^^^
一些基本的错误处理会出现这些错误:
$friendInfo = mysql_query("select userid, username from users where userid = '". $userExplode[$i]."' ");
if (!$friendInfo) {
// error!
echo mysql_error();
}
else {
$friend = mysql_fetch_array(....);
}
您必须对输入参数进行转义以防止 SQL 注入(inject),而不是直接在查询中使用它们。使用 mysql_real_escape_string()
最容易做到这一点。
$attendingUsers = mysql_query("Select acceptedInvites from events where eventID = ". mysql_real_escape_string($_GET['eventID'])." ");
您可以通过将 for
循环替换为使用 IN()
子句的查询来稍微改进此算法。不是遍历所有 friend ,而是通过将数组内爆到逗号分隔列表中来执行一个查询:
$userExplode = explode("~", $users);
// Implode them together with commas
// Don't forget to call mysql_real_escape_string() on these if necessary
$friendlist = implode(",", $userExplode);
// Actually, you could just do $friendlist = str_replace("~", ",", $users)
// and avoid doing either explode() or implode()...
// Then query with an IN () clause...
$friendInfo = mysql_query("select userid, username from users where userid IN ($friendlist)");
现在不需要在循环中执行查询,您只需要在循环中获取。这比一次又一次的查询效率要高得多。
关于php 和 mysql 查询问题 - 查询不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9204889/