Hi, I'm trying to show a list which was shown to me with 'myslqi'. Now I'm working with PDO but I can't get it to work. I don't understand the error it generates.
function listadoUsuarios(){
$db = new BaseDatos();
$db->conectar();
$sentencia = "SELECT * FROM Usuario";
$db->prepare($sentencia);
$sentencia->execute();
echo "<div id='listado'>";
echo "<table id='listadoUsuario' border=1 cellspacing=0>";
echo "<tr>";
echo "<th>".'Nombre completo'."</th>";
echo "<th>".'Correo'."</th>";
echo "<th>".'Teléfono'."</th>";
echo "<th>".'Dirección'."</th>";
echo "<th>".'Fecha de nacimiento'."</th>";
echo "</tr>";
while ($row = $sentencia->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<td>".$row['nombre'].', '.$row['apellido']."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['telefono']."</td>";
echo "<td>".$row['direccion'].', '.$row['cod_postal']."</td>";
echo "<td>".$row['fecha_nac'].' - '."</td>";
echo "<td><button class='btn_tabla'><a href='google.es'>Modificar</a></button></td>";
echo "<td><button class='btn_tabla_mal'><a href='google.es'>Eliminar</a></button></td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
There are two problems in the code:
You are not retrieving the result of prepare and run, in which you would have a result set that you could then read with one of the methods
fetch
later.Something like that:
And then to read:
From what you've commented on the error
Call to undefined method BaseDatos::query()
, it can be seen that you're also not retrieving an instance of your PDO connection, which would be returned by theconectar
.Also...
In this case you don't need to prepare the query, since there is nothing to prepare in it , because no data is involved from the outside.
So, you can do it with
query
:The problem is that it
$sentencia
is a string and does not have a methodprepare
. What you should do is assign the output of$db->prepare
to a variable (which is a PDOStatement)And then iterate using
$stmt->fetch(PDO::FETCH_ASSOC)
.That's about your code as you have it now. In case you are not using parameters for your query, A. Cedano is right, there is nothing to prepare.