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');
}
}