Increment variable with for and while loop together

1

Hello

I'm using a while loop in my PHP application, but I need to increment a variable called ($ i) but stop incrementing when I get the amount of records stored in the variable ($ qtde), how can I do this without use FOR loop?

$sql = "SELECT id, fabricante, fornecedor, nome FROM produtos";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
  //Quantiade de produtos encontrados
  $qtde = $result->num_rows;
  //Incrementar esta variável
  $i = 0; 
  while($row = $result->fetch_assoc())
  {

    $nome = $row['nome'];
    
    echo $nome;
    echo $i;

  }
}

Thank you

    
asked by anonymous 09.11.2017 / 17:56

1 answer

1

Increase $i within the loop, and change the condition to see if it has reached the maximum:

$qtde = $result->num_rows;
$i = 0; 
while($row = $result->fetch_assoc() && $i < $qtde) {
  $nome = $row['nome'];
  $i++;
}
    
09.11.2017 / 18:00