I am currently trying to work with PDO to avoid SQL Injection but honestly I am extremely green, I have already made my connection file to the database by PDO but I am not sure how I can make a query through a select and show the result in an echo
Here I have my Connection file (pdoconnexpo.php):
<?php
require_once 'pdodatosexpo.php';
$dsn = "pgsql:host=$host;port=$port;dbname=$db;user=$username;password=$password";
try{
// Crear la conexion a la base de datos postgresql
$conn2 = new PDO($dsn);
// Mostrar un mensaje si la conexion es efectiva
if($conn2){
echo "Conexión a la base de datos <strong>$db</strong> Exitosa!";
}
}catch (PDOException $e){
// Reportar mensaje de error
echo $e->getMessage();
}
And here I make my query and try to show the result, I imagine that the error is beginner's.
<?php
include ('pdoconnectexpo.php');
/*
$query = "SELECT usuario FROM usuarios WHERE usuario='luis'";
$result = pg_query($query);
$row = pg_fetch_assoc($result);
if ($result){
echo $row['usuario'];
}else{
echo "error en la consulta";
}
*/
include ('pdoconnectexpo.php');
$query = 'SELECT usuario FROM "public".usuarios WHERE usuario=:usuario';
$registros = $conn2->prepare( $query ); //Preparamos la consulta
$registros->execute( array(":usuario" => $usuario) ); //Le pasamos el valor al marcador, esto es un array por lo que soporta tanto valores requiera la query, separador por coma
$registros = $registros->fetchAll( PDO::FETCH_OBJ ); //convirtiendo el resultado en objetos para poder iterar en un ciclo.
$registros[0]->usuario;
foreach ( $registros as $datos){
echo $datos->usuario;
}
?>
When you work with postgres in your SQL you must include the schema in your query, if it does not have a name within the standard it must be enclosed in double quotes;
Then we proceed to execute the query;
Up to this point you have already executed your query and stored the result as objects in the variable
$registros
, if you want to access only the first record you can do it in the following way;Now if what you want is to go through all the records that exist within this result, you can do it with a
foreach
;