How to do a "while" of the number of rows in a query?

1

Does anyone know if in that PHP function - mysql_num_rows do I have to while in it? I need to break the total number of rows in the table. I tried to do:

$sql = "select ...";
$query = mysql_qery($sql);
$rows = mysql_num_rows($query);

while(!empty($rows)){

}

I tried !isset , variable = "" , variable = 0 but it loops infinitely and only takes the first range from the row block of the query, I also tried to make a for but also did not work.

I already tested with echo the variable returns from the screen.

Continue to do an infinite loop, I need this loop to take a range of lines, I declare two variables, one for the

$inicio = 0;

and the other to limit

$limit = 100;

The range would be the block between the start and limit and when looping increment the value of limit in the offset, already tried to do:

$offset = $offset+$limit; 

and

$offset = $offset+100;

Plus it takes only the first few lines and makes the infinite loop on that first line.

Does anyone have an idea how to solve this?

I wanted to change the variable $ offset every time I go to loop the value would be the value of the $ limit variable that will be fixed has how to do this dynamically in php

    
asked by anonymous 04.03.2016 / 12:17

1 answer

2

Do the following:

$query = mysql_query('SELECT * FROM tabela');
$linhas_afetadas = mysql_num_rows($query);
$limit = 100;

for ($offset = 0; $offset < $linhas_afetadas; $offset += $limit) {
    $query = mysql_query('SELECT * FROM tabela LIMIT ' . $limit . ' OFFSET ' . $offset);
    while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
        // $row é um registro da sua tabela
    }
}

In the given example, you will get the records of the DB from 100 to 100 , iterating over those 100 within while ($row ...) {} .

$row is an array, which will contain a record returned by its query , by iteration. Each array index will match a column in your table. If your table is:

+----+----------+-------+-------+
| id | nome     | idade | grupo |
+----+----------+-------+-------+

Then $row will contain the following structure at each iteration:

Array
(
    [0] => ID
    [1] => NOME
    [2] => IDADE
    [3] => GRUPO
)
    
04.03.2016 / 15:10