Add a value to while in php [closed]

-3

I have the following code:

<?php
  $con = mysqli_connect("localhost","root","","gibellino");
  mysqli_set_charset($con,"utf-8");
  $result = mysqli_query($con,"select * from index_img");

  while($row = mysqli_fetch_array($result)){
    $img = $row['img'];
    echo "<td><img src='../imagem/bd/index/$img' width='170px' height='300px'><a href='#'><img src='../imagem/fancy_closebox.png' id='fechar'></a></td>";
  }
}
?>

Well, and I wanted the while to have one more value than the database data number. Genre:

while($row = mysqli_fetch_array($result)+1)

I already tried +1 in while already tried to create row outside of while and add 1 but always gives me error .

    
asked by anonymous 07.12.2015 / 10:00

1 answer

2

The value being passed to while is not a n number as you are thinking, so it is not possible to make the +1 you wanted.

  while($row = mysqli_fetch_array($result))

The variable $row of the expression is receiving an array from the mysqli_fetch_array($result) function, and as long as this array is not empty, PHP will interpret as true% and when the data ends the expression will return TRUE which will be interpreted as NULL and then while will be stopped.

Note the following code:

while(TRUE) {
   // Trecho de código
}

The above code represents a loop (loopback) infinity , ie "never" will be stopped, unless a FALSE is added inside the loop .

But there is a way to do it the way you wanted, just use a counter instead of the expression break , example:

$nrows = mysqli_num_rows($result);
while($nrows){
   $nrows--;
   $row = mysqli_fetch_array($result);
   // Restante do código aqui
}

But the problem is that when the count is finished, where it has $row = ... , an index error will be thrown, since the variable $row['img'] will have the value $row , since it has finished the data. To get around this would have to add some if's and / or ternary operations, things totally unnecessary if you put the default image after the loop as in the example:

<?php
  $con = mysqli_connect("localhost","root","","gibellino");
  mysqli_set_charset($con,"utf-8");
  $result = mysqli_query($con,"select * from index_img");

  while($row = mysqli_fetch_array($result)){
    $img = $row['img'];
    echo "<td><img src='../imagem/bd/index/$img' width='170px' height='300px'><a href='#'><img src='../imagem/fancy_closebox.png' id='fechar'></a></td>";
  }

  // Aqui fora do loop vai a imagem padrão que será sempre adicionada após todas as demais.
  echo "<td><img src='../imagem/bd/index/aqui-vai-a-imagem-padrao.jpg' width='170px' height='300px'><a href='#'><img src='../imagem/fancy_closebox.png' id='fechar'></a></td>";
}
?>
    
07.12.2015 / 11:00