while/foreach/for get 3 results at a time?

I am trying to get 3 results out of a mysql database at a time (so it would display 3 at a time)

So it would be something like

$sql = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_array($sql)) {
    print $row['username'];
    print $row['username2'];
    print $row['username3'];
}

but $row['username']; and $row['username2']; $row['username3']; would just be the first second and third results out of the mysql table.

and then it would repeat and $row['username']; and $row['username2']; and $row['username3']; would be the 4th, 5th and 6th and so on.

Any idea of how I could do this?


You could do this:

function mysql_fetch_n_rows($rs, $n)
{
  $rows = array();
  while ($n-- && ($row = mysql_fetch_array($rs)))
  {
    $rows[] = $row;
  }

  return $rows;
}

$rs = mysql_query("SELECT * FROM table");

while ($rows = mysql_fetch_n_rows($rs, 3))
{
    print $rows[0]['username'];
    print $rows[1]['username'];
    print $rows[2]['username'];
}

(Disclaimer: obviously you'd need to verify that you actually got 3 rows back. You might only get one or two.)

But I doubt you really need the above code. Generally it's much easier to do a ($i % 3) as some of the other answers suggest. I definitely do not post this answer because I think it's the best general solution, but only as an example of creating a general purpose function instead of trying to hard code this type of solution within the while loop.


You can use limit clauses,

select * from table limit 1, 3

then for the next 3,

select * from table limit 4, 3

(you might want to look up the syntax, I may have the order backwards)


To show just the three results, you can do like this:

$sql = mysql_query("SELECT * FROM table");

$count = 0;
while ($row = mysql_fetch_array($sql)) {
    $count++;
    if ($count === 3) break; 
    print $row['username'];
}

Or if you want, you can specify the LIMIT clause in your query to fetch just three records:

$sql = mysql_query("SELECT * FROM table LIMIT 3");

while ($row = mysql_fetch_array($sql)) {
    print $row['username'];
}

With LIMIT clause, you can also specify the start index and number of rows to be returned like this:

$sql = mysql_query("SELECT * FROM table LIMIT 4, 3");

The above query will return 3 rows starting from 4th row.

链接地址: http://www.djcxy.com/p/75302.html

上一篇: mysql全文搜索问题

下一篇: while / foreach /一次获得3个结果?