Process select if count () is greater than zero

0

If some records meet the condition I want to show them on the screen. If no record meets the condition that shows a message. I have this code and I show the data using Smarty template. But it sends me a message that the $ matrix is not defined. The table has records. The code is this:

$BD = new ConexionDB();
$sql = "SELECT COUNT(*) FROM tabla WHERE campo = 'X'";
if ($sth = $BD->query($sql)) {
    if ($sth->fetchColumn() > 0) {
        $sql = "SELECT cod, nom FROM tabla WHERE campo = 'X'";
        while ($fila = $sth->fetch(PDO::FETCH_ASSOC)) {
            $matriz[] = new DatosVO($fila['cod'], $fila['nom']);
        }
        $NoRegistros = "";
    } else {
        $NoRegistros = "NO EXISTEN REGISTROS";
        $matriz = '';
    }
    $exito = TRUE;
}
$tpl = new Plantilla();
if ($exito) {
    $tpl->assign('NoRegistros', $NoRegistros);
    $tpl->assign('lista', $matriz);
    $tpl->display('mostrar.tpl.php');
} else {
    $tpl->assign('mensaje', $mensaje);
    $tpl->display('fallo.tpl.php');
}

I used the rowcount () in this way:

$sql = "SELECT cod, nom FROM tabla WHERE condicion = 'X'";
$sth = $BD->prepare($sql);
$sth->execute();

if ($sth->rowCount() > 0) {

    while ($fila = $sth->fetch(PDO::FETCH_ASSOC)) {
        $matriz[] = new DatosVO($fila['cod'], $fila['nom']);
    }
    $NoRegistros = "";

} else {
    $NoRegistros = "NO EXISTEN REGISTROS";
    $prenonomstuds = "";
}

But in the PHP manual link example # 2 says that rowcount does not return the records of a select and recommend using query ().

    
asked by Piropeator 27.04.2017 в 22:43
source

1 answer

2

Since you never run your second Query, you do not find ['cod'] nor ['nom'] and since your matrix is created within the while it is not defined when you call it in the assign.

If you define it before, it will always be marked by an empty table.

so you would need to make an empty array with $ array = []; and then fill it with your data, there is no point making two calls to your database just to know the length of the result, just call your second Query and if the matrix is empty it will have a size of 0.

$BD = new ConexionDB();
$sql = "SELECT cod, nom FROM tabla WHERE campo = 'X'";
$matriz=[];
if ($sth = $BD->query($sql)) {
    while ($fila = $sth->fetch(PDO::FETCH_ASSOC)) {
        $matriz[] = new DatosVO($fila['cod'], $fila['nom']);
    }
    if (count($matriz)==0){
        $NoRegistros = "NO EXISTEN REGISTROS";
    }
    $exito = TRUE;
}
$tpl = new Plantilla();
if ($exito) {
    $tpl->assign('NoRegistros', $NoRegistros);
    $tpl->assign('lista', $matriz);
    $tpl->display('mostrar.tpl.php');
} else {
    $tpl->assign('mensaje', $mensaje);
    $tpl->display('fallo.tpl.php');
}
    
answered by 27.04.2017 / 23:12
source