I want to make a single query of a table X , using PHP 's PDO , but I can't understand the logic of it very well so that within a single class I call the method to make a simple query.
I attach the example of what I have:
<?php
class prueba{
public static function conectar(){
try{
$cn= new PDO("mysql:host=localhost;dbname=prueba","root","noscope");
return $cn;
}catch (PDOException $ex){
die($ex->getMessege());
}
}
function consulta(){
$query = "SELECT * FROM prueba";
prueba::conectar();
$resultado = prueba::$cn->prepare($query);
$resultado->execute();
echo '<table>';
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>'.$id = $row['id'].'</td>';
echo '<td>'.$nombre = $row['nombre'].'</td>';
echo '<td>'.$tipo = $row ['tipo'].'</td>';
echo '<td>'.$detalle = $row ['detalle'].'</td>';
echo '</tr>';
}
echo '</table>';
}
}
$prueba = new prueba();
$prueba->consulta();
?>
And this is the error I get:
Fatal error: Uncaught Error: Call to undefined method PDOException::getMessege() in C:\wamp64\www\Interruption\prueba.php:14 Stack trace: #0 C:\wamp64\www\Interruption\prueba.php(26): prueba::conectar() #1 C:\wamp64\www\Interruption\prueba.php(52): prueba->consulta() #2 {main} thrown in C:\wamp64\www\Interruption\prueba.php on line 14
I honestly don't understand much about PDO and how it works other than making the connection. I appreciate your collaboration.
Correcting the syntax errors (connection string as Aldanux says, getMessege) you need to consider that the static method
prueba::conectar
returns the connection. Then you should do:EDIT You are printing the result wrong. Within your
<td>
you are assigning variables instead of printing them. It should be something like:By the way, this returns you a new connection every time you call
prueba::conectar
. It would be better to use the singleton pattern to put:You are calling the method wrong, you must not refer to the class, since you are inside it, you must call the method as follows: