$allUsersResult = mysql_query("SELECT * FROM users");
// the purpose of this line was to grab the first row for use
// separately in a different area than the while loop
$user = mysql_fetch_assoc($allUsersResult);
while($users = mysql_fetch_assoc($allUsersResult)){
// the first row is not available here
}
这是一个错误还是我做错了我的错?
PS:这只是举例。我没有像这样使用$ user和while循环,它们在脚本的不同位置使用。
答案 0 :(得分:13)
你需要放弃
$allUsers = mysql_fetch_assoc($allUsersResult);
这是你的第一个结果行。
回答新问题:不。这不是PHP的设计缺陷。这是程序设计中的一个缺陷。你需要重新思考你在做什么。
为什么需要分离出第一个值?您是否一直依赖它来自您的桌子中的特定行?如果您更改了表格架构,那么非常可能将使用其他排序顺序将结果返回给您。
也许如果你告诉我们你想做什么,我们可以给你一些设计建议。
答案 1 :(得分:10)
这是你的错。首先调用$allUsers = mysql_fetch_assoc($allUsersResult);
,您已经从结果集中获取第一行。所以只需删除该行,它应该按预期工作。
编辑:评论中的每个请求。
$user = mysql_fetch_assoc($allUsersResult);
if ( $user ) // check if we actually have a result
{
// do something special with first $user
do
{
// do the general stuff with user
}
while( $user = mysql_fetch_assoc($allUsersResult) );
}
答案 2 :(得分:0)
某些IDE认为这是错误的代码(一行中有两个语句)。更好:
$allUsersResult = mysql_query("SELECT * FROM users");
$user = mysql_fetch_assoc($allUsersResult);
while($user){
// do stuff
doStuff($user)
// at last: get next result
$user = mysql_fetch_assoc($allUsersResult)
}
答案 3 :(得分:0)
使用mysql_fetch_assoc()
时,基本上是检索行,然后推进内部结果指针+1。
为了更好地解释,这是您的代码:
$allUsersResult = mysql_query("SELECT * FROM users");
//Result is into $allUsersResult... Pointer at 0
$user = mysql_fetch_assoc($allUsersResult);
// $user now holds first row (0), advancing pointer to 1
// Here, it will fetch second row as pointer is at 1...
while($users = mysql_fetch_assoc($allUsersResult)){
// the first row is not available here
}
如果您想再次获取第一行,不需要再次运行查询,只需在读完第一行后将指针重置为0 ...
$allUsersResult = mysql_query("SELECT * FROM users");
//Result is into $allUsersResult... Pointer at 0
$user = mysql_fetch_assoc($allUsersResult);
// $user now holds first row (0), advancing pointer to 1
// Resetting pointer to 0
mysql_data_seek($allUsersResult, 0);
// Here, it will fetch all rows starting with the first one
while($users = mysql_fetch_assoc($allUsersResult)){
// And the first row IS available
}
答案 4 :(得分:-1)
我会继续回答我自己的问题:
$allUsersResult = mysql_query("SELECT * FROM users");
// transfer all rows to your own array immediately
while($user = mysql_fetch_assoc($allUsersResult)){
$allUsers[] = $user;
}
// use first row however you like anywhere in your code
$firstRow = $allUsers[0];
// use all rows however you like anywhere in your code
foreach($allUsers as $user){
// do whatever with each row ($user). Hey look they're all here! :)
}