MySQL添加到查询会使现有部件无效

时间:2012-12-18 10:53:28

标签: php mysql sql

数据库:

  • xx_users(id,name,user_id,email,location)
  • xx_questions(id,question,description,user_id)

原始代码:

$friends = $facebook->api('/me/friends');
$arr= $friends['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
    $friend_ids_arr[] = $friend['id'];
}

$sql = "SELECT * FROM xx_questions WHERE user_id IN (" . implode(',', $friend_ids_arr) . ") OR user_id = '$user' ORDER BY time DESC";

新代码:

$friends = $facebook->api('/me/friends');
$arr= $friends['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
    $friend_ids_arr[] = $friend['id'];
}
    $sql = "SELECT *
    FROM xx_questions q JOIN xx_users u ON
        q.user_id = u.user_id
    WHERE q.user_id IN (implode(',', $friend_ids_arr)) OR // STEP 1
        q.user_id = '$user' OR // STEP 2
        u.location = (SELECT location FROM xx_users WHERE user_id = $user) // STEP 3
    ORDER BY q .time DESC";

    $data = mysql_query($sql) or die(mysql_error());
    while ($row = mysql_fetch_assoc($data)) {
        echo $row[id];
        }

如果出现以下三种情况,我试图从xx_questions(用户发布)中选择问题:

  1. 海报的user_id与当前用户的朋友之一(即海报和用户是朋友)匹配的值
  2. 海报的user_id与用户的user_id匹配的那些值(即海报是用户)
  3. 海报的位置与当前用户的位置相匹配的那些值(即海报和用户目前位于同一城市)
  4. 我最初实现了第1步和第2步,但是当我添加第3步时,会发生两件事:

    1. 步骤1停止工作(即仅返回当前用户的帖子和同一城市的人员)
    2. while循环中回显的$row[id]是xx_users,而不是xx_questions。我试过$row[q.id],但无济于事。
    3. 知道出了什么问题吗?

1 个答案:

答案 0 :(得分:2)

在你的秒查询中,你的内爆语句不在字符串之外。

"WHERE q.user_id IN (implode(',', $friend_ids_arr)) OR" // STEP 1

虽然php可以将变量添加到双引号字符串($x = "test $test test" $ test将更改为$ test的值)但它无法转义函数。所以这将返回

"WHERE q.user_id IN (implode(',', Array)) OR" // STEP 1

您应该使用:

"WHERE q.user_id IN (".implode(',', $friend_ids_arr).") OR" // STEP 1

最后您使用的是SELECT *,如果两个表都有Id列,则只返回一个。最好使用SELECT q.*来获取问题行或SELECT q.*, u.location来获取整个问题行和用户表中的位置。

我还检查了你的查询,它应该做你想做的事情

$sql = "SELECT q.*, u.location
            FROM xx_questions q 
            JOIN xx_users u 
            ON q.user_id = u.user_id
            WHERE q.user_id IN (".implode(',', $friend_ids_arr).") OR // STEP 1
            q.user_id = $user OR // STEP 2
            u.location = (SELECT location FROM xx_users WHERE user_id = $user) // STEP 3
            ORDER BY q.time DESC";

我唯一改变的是implode并删除了$user周围的''。这是因为$ user不是一个整数,而是一个包含数字的字符串,但是附加了一些额外的空格(例如'1'而不是'1');