Increment variable with loop for and while together

Asked

Viewed 339 times

1

Hello

I’m using a while loop in my PHP application, but I need to increment a variable named ( $i ) but stop incrementing when I get the amount of records stored in the variable ( $Qtde ), as I can do this without using 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

1 answer

1


Increment $i inside the loop, and change the condition to check whether you arrived at the maximum:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.