Difference between loop while and foreach

0

I have two codes to list a query, the connection is with PDO.

$BD = new ConexionDB();
$sql = "SELECT cod, nom from tabla";
$sth = $BD->prepare($sql);
$sth->execute();

$valor = 0;
foreach($sth as $fila) {
    $valor++;
    echo $valor." ";
    echo $fila['cod'];
    echo "</br>";
}

And this one:

$BD = new ConexionDB();
$sql = "SELECT cod, nom from tabla";
$sth = $BD->prepare($sql);
$sth->execute();

$valor = 0;
while ($fila = $sth->fetch(PDO::FETCH_ASSOC)) {
    $valor++;
    echo $valor." ";
    echo $fila['cod'];
    echo "</br>";
}

Both codes work, but what is the optimal way to do it? If I want to make an UPDATE to the table with an incremental value placing this code inside the loop in each case:

$sql= "UPDATE tabla SET orden = ".$valor." WHERE cod = ".$fila['cod'];
$sth = $BD->prepare($sql);
$sth->execute();

Works with the foreach but does not work within the while, showing this error:

  

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE [HY000]: General error' in line (where the while is)

    
asked by Piropeator 11.01.2017 в 18:31
source

2 answers

1

The foreach iterates, that is, it becomes each element of the collection and its duration is equal to the number of elements that exist in the collection, it is the most optimal way to handle list elements.

The while is a cycle that runs until the condition is false and not necessarily only for collections :)

    
answered by 11.01.2017 / 18:38
source
1

That I only know in MySQL / MySQLi you could do the while , I think the best way would be to select everything and automatically convert it to an array.

Something like this:

$BD = new ConexionDB();
$sql = "SELECT cod, nom from tabla";
$sth = $BD->prepare($sql);
$sth->execute();
$filas = $sth->fetchAll(PDO::FETCH_ASSOC);
$valor = 0;
foreach($filas as $fila) {
    $valor++;
    echo $valor." ";
    echo $fila['cod'];
    echo "</br>";
}
    
answered by 11.01.2017 в 20:47