php 和 mysql 查询问题 - 查询不工作

标签 php mysql for-loop while-loop

我正在尝试创建属于某个组的用户表,但我似乎无法让它工作。该列表存储在一列中,以便每个用户 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/

相关文章:

javascript - 如果 php 中存在匹配项,如何在静态下拉列表中设置 jQuery 变量值

php - 计算两个时间字段之间的差异

mysql - Docker "Can' t 通过socket连接本地MySQL服务器"

带有 While 循环的 PHP 表单仅发送最后一个 $_POST 复选框

R 多元回归循环和提取系数

C编程: Reverse ordered list

php - 如何从 .dll 文件生成 .php 文件以完成代码?

javascript - SMTPJS 脚本似乎不起作用

php - 如何在 MySQL 和 PHP 中处理日期和时间?

MySqlWhereANDOR条件,返回所有数据?