简体   繁体   English

在PHP中循环MySQL查询结果

[英]looping MySQL query result in PHP

$b = 1;
$d = mysql_query("select *from 'table_name'");
while($b < 10){
    while($e = mysql_fetch_array($d)){
        echo $e['name_field'];
    }
    $b++;
}

I want to loop the output, but I'm stuck. 我想循环输出,但是卡住了。 I've tried but still got nothing. 我已经尝试过,但仍然一无所获。 something like this : 像这样的东西:

<?php
$a = 0; 
$b = 0;
for($a=0;$a<10;$a++){
    for($b=0;$b<10;$b++){
        echo $b;        
    }
}

Seperate * and FROM by a space. 用空格分隔*FROM Use backticks or no delimiters instead of single quotes for the table name. 表名使用反引号或不使用定界符,而不是单引号。

If you want to limit your result, add a LIMIT expression to your query: 如果要限制结果,请向查询中添加LIMIT表达式:

SELECT * FROM `table_name` LIMIT 10

And then loop through the results: 然后遍历结果:

while($row = mysql_fetch_array($d)){
     echo $row['name_field'];
}

You aren't incrementing $b anywhere. 您不会在任何地方增加$ b。 It gets set as 1 and never increased, so it will always be less than 10. 它设置为1且从不增加,因此始终小于10。

Your query is wrong as table name should not be in single quote you can use backticks. 您的查询是错误的,因为表名不应用单引号引起来,您可以使用反引号。

if you want to limit result to show only 10 rows add LIMIT in query this should be 如果您想将结果限制为仅显示10行,请在查询中添加LIMIT ,这应为

$d = mysql_query("select * from `table_name` limit 10");

Remove outer loop 去除外圈

while($e = mysql_fetch_array($d)){
     echo $e['name_field'];
}

EDIT 编辑

You might want the result to be shown 10 times. 您可能希望结果显示10次。 Just put the query inside the outer while loop. 只需将查询放入外部while循环中即可。

$b = 0;
while($b < 10)
{
      $d = mysql_query("select * from `table_name`");
      while($e = mysql_fetch_array($d))
      {
        echo $e['name_field'];
      }
      $b++;
}
$d = mysql_query("select *from `table_name` LIMIT 10");  // use back-ticks and limit in query

while($e = mysql_fetch_array($d)){
     echo $e['name_field'];
}

If you mean that you want to output 'name_field' for the first 9 rows (1..<10), you would use: 如果您想在前9行(1 .. <10)中输出'name_field',则可以使用:

$d = mysql_query("SELECT * FROM `table_name` LIMIT 9");
while ($e = mysql_fetch_array($d)) {
    echo $e['name_field'];
}

If you, however, want to output 'name_field' for all rows 9 times (1..<10) in a loop construction, you only need to add the following two lines in the end of the loop: 但是,如果要在循环构造中为所有行输出9次(1 .. <10)的“ name_field”,则只需在循环末尾添加以下两行:

    mysql_data_seek($d, 0);
    $b++;

The resulting code would be: 结果代码为:

$b = 1;
$d = mysql_query("SELECT * FROM `table_name` LIMIT 9");
while ($b < 10) {
    while ($e = mysql_fetch_array($d)) {
        echo $e['name_field'];
    }
    mysql_data_seek($d, 0);
    $b++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM