How to go through PDO query in PHP

0

I have an application where I need to obtain the values of a query made:

I tried this way and if it worked (with mysqli):

//para conectarse a la Base de Datos    
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db   = 'incidencias';
$conexion = mysqli_connect( $host, $user, $pass, $db );
  if ($conexion == false) {
     echo 'Error al conectar a db';
     die();
  }

//para ejecutar una consulta
$sql = "consulta"
$query = mysqli_query($conexion, $sql);    

//para recorrer una consulta
if ($query) { 
while ($row = mysqli_fetch_assoc($query)){
    $row['compoConsultado']; 
}

Now I need to do the same but using the php PDO. For example:

//para conectarse a la Base de Datos
$dsn='mysql: host=172.0.0.1; dbname=incidencias';
$usuario='root';
$password='';
  try{
     $conexion=new PDO($dsn,$usuario,$password);
  }catch(PDOException $e){
     die('Error al conectarse a la base de datos: <br>'.$e->getMessage());
  }

//para realizar una consulta
try{
      $query=$conexion->prepare($sql);
      $query->execute();
    }catch(PDOException $e){
      die('Error en la consulta: <br>'.$e->getMessage());
    }
//para recorrer la consulta
//nose como es hace :( 

What I do not know, is how to access the fields of the query, so consult a table

Users who have: - user_id - first name - telephone

In the first example I could eg. ask if the id of a user was equal to 1 with:

//dentro del while del ej con mysqli
if($row[id_usuario] == 1 ){
  //codigo..
}

worse I can not do it consulting by PDO, I tried many ways without successes.

Thanks in advance to anyone who can contribute.

    
asked by Cesar Paliza 08.05.2017 в 05:05
source

1 answer

2

Very important : PDO requires a series of parameters without which the connection would not be secure, for example, if it is used without the try ... catch block and there are errors, it could be revealing the password in the file error_log , also if the emulation of queries is not deactivated a malicious user could inject malicious queries in the BD. The best thing to do is to have a single class dedicated to creating the connection and that well-configured class .

Here is a basic example to use PDO.

This is a function that returns the connection or null . In any case it is best to have a class dedicated to the connection.

A. We created the connection

function getPDO () {

try {
    $pdo = new PDO('mysql:host=localhost;dbname=prueba', $usuario, $pwd);
    return $pdo;
    }
} catch (PDOException $e) {
    print "¡Error!: <br/>";
    return null;
}

B. Retrieve PDO object and send query

We store in $pdo the returned object by calling the previous function. And we ask if it is valid or is null

 $pdo=getPDO();

 if ($pdo) 
 {

      $sql = "SELECT id_usuario, nombre FROM personas;";
      $stmt = $pdo->prepare($sql);
      $stmt->execute(); 

      //Aquí, cualquiera de los dos procedimientos explicados en b1 y b2. 

  } else {
      echo "Hubo un problema con la conexión";
  }

The data can be read in two ways:

b1. Almost the same as MySQLi:

 while ($arr = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $arr['id_usuario'];
    echo $arr['nombre'];

 }

b2. Using a for loop:

$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
 foreach ($arr as $row) {
    echo $row['id_usuario'];
    echo $row['nombre'];

 }

Note 1:

PDO is much more likely to get the result of the query. Here PDO::FETCH_ASSOC has been used, but here are many other ways .

Note 2.

If you want to choose a Clase dedicated to the connection, you can use this, or be inspired by that model: PHP-PDO .

    
answered by 08.05.2017 в 05:30