Problems with postgresql prepared queries?

1

I'm doing a query prepare to avoid the sql injection, but I did not run the page that should show the result, it gives error and I think it's because the functions I'm using are from mysqli, and I'm working with postgresql, I'm not sure if these work they serve with postgres and for that reason the errors, if so, how would the queries prepared with postgres be done?

$busqueda = $_GET['resultado'];

$query = "select * from datos where nombre = ?";

$resultado = pg_prepare($conexion, $query);

$consulta = pg_stmt_bind_param($resultado, "s", $busqueda);
$consulta = pg_stmt_execute($resultado);

if($consulta == false){

    echo "Error en consulta";
}else{

    $consulta = pg_stmt_bind_result($resultado, $nombre, $apellido, $telefono);

    while(pg_stmt_fetch($resultado)){

        echo $nombre . " " . $apellido . " " . $telefono;
    }

    pg_stmt_close($resultado);
}
    
asked by Edwin Aquino 05.08.2017 в 00:51
source

1 answer

2

The documentation regarding Postgresql is somewhat poor and scattered. In addition, prepared queries work somewhat differently. Unless you opt for PDO , which would not be a bad idea, since except for small changes with respect to the connection, the call to consultation methods, prepare queries, get the results, etc. It is invariable.

In this answer I have tried to gather a code that works for you.

I make some comments in the code.

I hope it serves you.

<?php

/* Conectar: actualizar con datos reales */

$conn_string = "host=tu-host port=5432 dbname=nombrebd user=usuario password=clave";
$conn = pg_connect($conn_string);

/* Verificar si la conexión tuvo éxito */

if (!$conn) 
{

  echo "Hubo un error!\n";

}else{

    /* Con postgresql se usa $1, $2 ... en lugar de ? o marcadores de :nombre */

    $sql="SELECT nombre, apellido FROM datos WHERE nombre = $1";
    $busqueda="Valor a buscar";

    /* Preparar la consulta */

    $result = pg_prepare($conn, "my_query", $sql);

    /* Ejecutar la consulta */

    $result = pg_execute($conn, "my_query", array($busqueda));

    /* Verificar si no hubo resultados */

    if (!$result) {

        echo "No se encontraron datos o la consulta no tuvo éxito.\n";

    }else{

        /* Una posibilidad: Leer resultados por filas*/

        while ($row = pg_fetch_row($result)) 
        {
            echo "Nombre: ".$row[0] . "Apellido: ". $row[1]."<br>";
        }

        /* Otra posibilidad: Leer resultados como un arreglo*/

        while ($row = pg_fetch_array($result)) 
        { 
            echo "Nombre: ".$row["nombre"] . "Apellido: ". $row["apellido"]."<br>";
        } 

    } 

/* Cerrar conexión */

pg_close($conn);

}   

?>
    
answered by 05.08.2017 / 05:15
source