S
S
serbinyo2014-03-12 20:53:48
Database
serbinyo, 2014-03-12 20:53:48

Why does DO WHILE loop work but WHILE loop not with mysql_fetch_array() function?

Have a MySQL database

$result = mysql_query ('SELECT * FROM cars WHERE kuzov="универсал" AND year="2007"',$db);
$row = mysql_fetch_array ($result);

Please explain why the DO WHILE loop works
do 
  {
    echo " <p>Автомобиль - $row[auto]<br/> Кузов - $row[kuzov]<br/> Год выпуска - $row[year]<br/> Пробег машины - $row[probeg];</p> ";
  }
  while ($row = mysql_fetch_array ($result));

There is no WHILE loop
while ($row = mysql_fetch_array ($result))
  {	
    echo " <p>Автомобиль - $row[auto]<br/> Кузов - $row[kuzov]<br/> Год выпуска - $row[year]<br/> Пробег машины - $row[probeg];</p> ";	
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2014-03-13
@serbinyo

I can assume that the query result is one line. In the case of WHILE, you start output from the second line, since the condition with the request for the next line is evaluated and checked before the execution of the loop body, and the first line is requested from you before the start of the loop and is not used.

A
Andrey Tokmakov, 2014-03-13
@NPC

If you really want to use while, do this:

$result = mysql_query ('SELECT * FROM cars WHERE kuzov="универсал" AND year="2007"',$db);
$row = mysql_fetch_array ($result);

$i = 0;

while ( $row[$i] )
  {	
    echo " <p>Автомобиль - $row[$i][auto]<br/> Кузов - $row[$i][kuzov]<br/> Год выпуска - $row[$i][year]<br/> Пробег машины - $row[$i][probeg];</p> ";
$i++;	
  }

and everything will work. But it's better not to do this, do it through foreach:
$result = mysql_query ('SELECT * FROM cars WHERE kuzov="универсал" AND year="2007"',$db);
$rows = mysql_fetch_array ($result);

foreach ( $rows as $row )
  {	
    echo " <p>Автомобиль - $row[auto]<br/> Кузов - $row[kuzov]<br/> Год выпуска - $row[year]<br/> Пробег машины - $row[probeg];</p> ";
  }

That will be better

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question