I have the following PDO query to show a balance brought from the DB:
View
<?php
$item = "documento";
$valor = $documento;
$saldo = ControladorCuadros::ctrMostrarSaldo($item, $valor);
foreach ($saldo as $key => $value) {
$saldo = $value["saldo"];
}
?>
Controller
static public function ctrMostrarSaldo($item, $valor){
$tabla = "datos";
$respuesta = ModeloCuadros::mdlMostrarSaldo($tabla, $item, $valor);
return $respuesta;
}
Model
static public function mdlMostrarSaldo($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt -> close();
$stmt = null;
}
So far, so good... It shows me the balance when the document exists in the table but if it doesn't, it shows this error: Notice: Array to string conversion in C:\xampp\htdocs...\vista.php.
How can I validate if the document does not exist to show me the value in zero?
Considering what the PHP Manual says about
fetchAll
:You can use a ternary operator that evaluates the result of
fetchAll
, returning that result or0
.Correcting the logic error when receiving the data
Since it will
mdlMostrarSaldo
return0
if there are no results, you must adapt the code where you read the result of the call to that function. When it returns0
you can't use aforeach
to read the data, because0
it's not an array. So you have to do something like this: