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)