Infinite loop in PHP

0

Hi, I've started to see the object-oriented programming in php and I'm doing an exercise in which I make an sql query in which I want to show all the news that I have but it generates an infinite loop of the first news that I have saved. I think it's because I'm doing a while with the query but I do not know how to fix it.

Code:

    $objetoBBDD = new baseDatos();
    $consulta = "SELECT * FROM noticias";

    while($fila = mysqli_fetch_array($objetoBBDD->consultarBD($consulta)))
    {
        if($fila[4]==0)
            $fila[4]="No";
        else
            $fila[4]="Si";

        echo "Numero de la noticia: ".$fila[0]."<br> Titulo: ".$fila[1]."<br> Descripcion: ".$fila[2].
                "<br> Fecha: ".$fila[3]."<br> Publicada: ".$fila[4].'<br><br>';
    }
    
asked by Mario Guiber 09.11.2017 в 18:09
source

2 answers

2

The infinite loop is obvious, every time you return to while you call the consultarBD method again, so it will never end. The ideal would be to obtain the result before the while to then iterate with a while or with a foreach , also could have ignored the if else to use a ternary in the echo .

$objetoBBDD = new baseDatos();
$consulta = "SELECT * FROM noticias";
$resultado = $objetoBBDD->consultarBD($consulta);//obtenemos los resultados
while($fila = mysqli_fetch_array($resultado))
{
    echo "Numero de la noticia: ".$fila[0]."<br> Titulo: ".$fila[1].
         "<br> Descripcion: ".$fila[2].
         "<br> Fecha: ".$fila[3]."<br> Publicada: ".(($fila[4]==0)?"NO":"SI").'<br><br>';
}

For the comments I think you try to adapt to POO mysqli_fetch_array this is done based on the results.

$objetoBBDD = new baseDatos();
$consulta = "SELECT * FROM noticias";
$resultado = $objetoBBDD->consultarBD($consulta);//obtenemos los resultados
while($fila = $resultado->fetch_array(MYSQLI_NUM))
{
   echo "Numero de la noticia: ".$fila[0]."<br> Titulo: ".$fila[1].
         "<br> Descripcion: ".$fila[2].
         "<br> Fecha: ".$fila[3]."<br> Publicada: ".(($fila[4]==0)?"NO":"SI").'<br><br>';
}
    
answered by 09.11.2017 / 18:30
source
1

Use a foreach instead of a while:

$resultado = mysqli_fetch_all($objetoBBDD->consultarBD($consulta), MYSQLI_NUM);
foreach ($resultado as $fila)
{
    if($fila[4]==0)
        $fila[4]="No";
    else
        $fila[4]="Si";

    echo "Numero de la noticia: ".$fila[0]."<br> Titulo: ".$fila[1]."<br> Descripcion: ".$fila[2].
            "<br> Fecha: ".$fila[3]."<br> Publicada: ".$fila[4].'<br><br>';
}
    
answered by 09.11.2017 в 18:30