Problems retrieving fetch records ()

0

This class obtains the records in the table. The select has only some fields in the table. I have some questions:
1) Why does $ records only save the last record if it is inside the while?
2) The result of the query is within $ row , is it necessary to identify the fields with the setters (view)? Or can I do that outside of class?

public function listarDatos() {
    try {
            $sql = "SELECT campo1, campo2, campo3 FROM tabla WHERE campo4 = condicion";
            $bd = new Conn();
            $stmt = $bd->prepare($sql);
            $stmt->execute();
            if ($stmt->rowCount() > 0) { 
                $registros = new registrosVista();
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
                {
                    $registros->setCampo1( $row['campo1'] );
                    $registros->setCampo2( $row['campo2'] );
                    $registros->setCampo3( $row['campo3'] );
                }
            } else { 
                $registros = NULL;
            }
            return $registros;
        } catch (Exception $e) {
            die ('No se puede ejecutar la consulta');
        }
}
    
asked by Piropeator 22.05.2018 в 01:59
source

1 answer

1

The problem is that every time you iterate in your while you overwrite the values. What you need is an array of objects like this:

public function listarDatos() {
try {
        $sql = "SELECT campo1, campo2, campo3 FROM tabla WHERE campo4 = condicion";
        $bd = new Conn();
        $stmt = $bd->prepare($sql);
        $stmt->execute();
        if ($stmt->rowCount() > 0) { 
            $registros = array();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
            {
                $registro = new registrosVista();
                $registro->setCampo1( $row['campo1'] );
                $registro->setCampo2( $row['campo2'] );
                $registro->setCampo3( $row['campo3'] );
                $registros[] = $registro;
            }
        } else { 
            $registros = NULL;
        }
        return $registros;
    } catch (Exception $e) {
        die ('No se puede ejecutar la consulta');
    }
}
    
answered by 22.05.2018 / 02:03
source