【问题标题】:php and mysql query trouble - query isn't workingphp 和 mysql 查询问题 - 查询不工作
【发布时间】:2012-03-01 13:42:22
【问题描述】:

我正在尝试创建一个属于某个组的用户表,但我似乎无法使其正常工作。该列表存储在一列中,因此每个用户 ID # 都由“~”分隔。例如,如果用户 1,2 和 3 正在参加该列,则该列将显示“1~2~3”。这就是我使用爆炸的目的。

我收到以下错误“警告:mysql_fetch_array() 期望参数 1 是资源,布尔值给出”这是定义 $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 有关,因为当我回显它时,什么都没有显示(通常会说数组)。

【问题讨论】:

  • 不错的 sql 注入孔。希望你喜欢有人会开车穿过它并停在你的服务器中间的卡车。

标签: php mysql for-loop while-loop


【解决方案1】:

这里有一些问题。您遇到的主要问题是查询中没有错误处理和语法错误。选择列表列周围不应有括号:

$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 注入,而不是直接在查询中使用它们。使用mysql_real_escape_string() 最容易做到这一点。

$attendingUsers = mysql_query("Select acceptedInvites from events where eventID = ". mysql_real_escape_string($_GET['eventID'])." ");

您可以通过将for 循环替换为使用IN() 子句的查询来稍微改进此算法。不用遍历所有朋友,而是通过将数组内爆到逗号分隔的列表中来执行一次查询:

$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)");

现在,您无需在循环中执行查询,而只需在循环中获取。这比一次又一次地查询要高效得多。

【讨论】:

  • 哇,这么简单的错误。我不敢相信我没有注意到这一点,我想是时候休息一下了。感谢您的帮助!
猜你喜欢
  • 2018-09-26
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多