1

在我的本地 xampp 上运行 while 脚本时,它只会一遍又一遍地返回相同的结果,这是我正在使用的 PHP:

<?php
$id = $_GET['id'];
$getmembers = mysql_query("SELECT * FROM group_memberships WHERE groupid = $id LIMIT 10");
$getids = mysql_fetch_assoc($getmembers);
    while($id = $getids['userid']){
        $getusers = mysql_fetch_assoc(mysql_query("SELECT look, username FROM users WHERE id = '$id'"));
        echo ($getusers['username']);
        echo('<br />');
    }
?>

我执行时得到的只是: http: //prntscr.com/12nh6g我的数据库包含注册到该组的 4 个不同用户。我不确定在 MySQL 中加入表,因为我不知道该怎么做。

如果我添加一个休息时间;那么它只返回一个结果,而不是超时。

任何帮助深表感谢!

我也很抱歉 PHP 的混乱程度,我是新手。

4

4 回答 4

1

在您的代码中:

<?php
$id = $_GET['id'];
$getmembers = mysql_query("SELECT * FROM group_memberships WHERE groupid = $id LIMIT 10");
$getids = mysql_fetch_assoc($getmembers);
    while($id = $getids['userid']){
        $getusers = mysql_fetch_assoc(mysql_query("SELECT look, username FROM users WHERE id = '$id'"));
        echo ($getusers['username']);
        echo('<br />');
    }
?>

告诉 PHP在 $id 分配给 $getids['userid'] 的值时“执行循环”

因此,您将有一个无限循环,因为 $id 一直被分配(并且总是具有相同的值) $getids 在 while 循环内永远不会改变。

但即使 $getids 即将更改,它仍将处于无限循环中,因为循环不检查 $id 是否为 $getids['userid']的值,它只是分配值。

于 2013-04-29T09:13:53.143 回答
1
while($id = $getids['userid']){ #This condition will always be true.

在如下循环中使用您的mysql_fetch_assoc语句。

while ($getids = mysql_fetch_assoc($getmembers)) {
    $id = $getids['userid']
    $getusers = mysql_fetch_assoc(mysql_query("SELECT look, username FROM users WHERE id = '$id'"));
    echo $getusers['username'];
    echo '<br />';
}

对于子查询,您可以尝试,

SELECT look, username FROM users
WHERE id IN 
       (SELECT userId FROM group_memberships
        WHERE groupid = $id
        LIMIT 10)

使用JOIN

SELECT u.look,u.username
FROM users as u
LEFT JOIN group_memberships as gm
     on gm.userId = u.id 
     WHERE gm.groupid = $id
     LIMIT 10 

注意: 请不要mysql_*在新代码中使用函数。它们不再被维护并被正式弃用。看到红框了吗?改为了解准备好的语句,并使用PDOMySQLi -本文将帮助您决定使用哪个。如果您选择 PDO,这里有一个很好的教程

于 2013-04-29T09:08:00.373 回答
1
<?php
$id = $_GET['id'];
$getmembers = mysql_query("SELECT * FROM group_memberships WHERE groupid = $id LIMIT 10");

    while($getids = mysql_fetch_assoc($getmembers)){
    $getusers = mysql_fetch_assoc(mysql_query("SELECT look, username FROM users WHERE id = '$id'"));
    echo ($getusers['username']);
    echo('<br />');
    }
?>

你有 while 循环错误,你需要在 while 循环中进行提取,所以它会一直持续到提取停止。

于 2013-04-29T09:22:08.723 回答
1
<?php

$id = (int) $_GET['id']; // very important part here, I cast the id to int, else you have a SQL injection leak
$getmembers = mysql_query("SELECT * FROM group_memberships WHERE groupid = $id LIMIT 10");
while ($membership = mysql_fetch_assoc($getmembers)) // on each pass we take a new result off first query
{
    $user = mysql_fetch_assoc(mysql_query("SELECT look, username FROM users WHERE id = '".$membership['user_id']."'"));
    echo ($user['username']);
    echo('<br />');
}
?>
于 2013-04-29T09:08:48.617 回答