2012-12-10 68 views
0

在这个脚本中,我基本上想要在某个行记录与浏览器地址栏中的名称匹配时从mysql表中回显数据。但由于某种原因,没有数据被回应。任何原因,我的while循环不起作用?我的while循环将不起作用

$users = $_GET['username']; 



$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'"); 
$other_friend_assoc = mysql_fetch_assoc($other_friend_query); 


while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) { 
    $friend_related = $other_friend_assoc['RelatedUser']; 
     echo $friend_related; 




    } 
+12

欢迎来到Stack Overflow! [**请不要在新代码中使用'mysql_ *'函数**](http://bit.ly/phpmsql)。他们不再被维护[并被正式弃用](https://wiki.php.net/rfc/mysql_deprecation)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。如果你选择PDO,[这里是一个很好的教程](http://j.mp/PoWehJ)。 –

+0

只需添加到@MadaraUchiha所说的内容 - 您当前的代码不会检查任何错误并且具有SQL注入漏洞。 – Cfreak

回答

3

那是因为您在while循环之前调用mysql_fetch_assoc。当你调用它时,它会提取结果。然后,当你进入你的循环时,结果已经被提取。只要删除,你会很好去。正如评论中所述,请停止使用mysql_函数。下面的代码将跳过您的发布变量,并检查错误。使用列列表代替SELECT *也是更好的做法。

$users = mysql_real_escape_string($_GET['username']); 

$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'") or die(mysql_error()); 

while($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) { 
    $friend_related = $other_friend_assoc['RelatedUser']; 
    echo $friend_related; 
} 
1

我的while循环无法正常工作的原因?

可能不是唯一的原因,但你正在跳过第一个结果。

// the following line is unused and therefore unnecessary 
$other_friend_assoc = mysql_fetch_assoc($other_friend_query); 

while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) {