Put the result of an sql query in a variable with PHP PDO [closed]

1
<?php

    try {

    $nombre=$_GET["nombre"];
    $password=$_GET["pass"];


    $base=new PDO ("mysql:host=localhost; dbname=te_la_juegas","root", "");
    $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    $sql="select nombre, pass from usuarios where nombre= :nombre and pass= :pass";
    //--EL--POKEMON--

    $pokemon="select pokemon from usuarios where nombre= :nombre ";
    $resultado=$base->prepare($sql);// PARA COMPROBAR QUE ESTAN EN BASE DATOS
    $eleccion=$base->prepare($pokemon);//PARA SABER EL POKEMON

    $resultado->bindValue(":nombre",$nombre);
    $resultado->bindValue(":pass",$password);// PARA COMPROBAR QUE ESTAN EN BASE DATOS
    $eleccion->bindValue(":nombre",$nombre);//PARA SABER EL POKEMON

    $resultado->execute();
    $eleccion->execute();

    //******************************************************************

    $numero_registro=$resultado->rowCount();
    $inicial=mysql_fetch_row($pokemon);

    if ($numero_registro!=0) {

      if ($inicial=="charmander") {
        # code...
      }elseif ($inicial=="vulvasaur") {
        # code...
      }else {

      }

    }else {
      header("location:index.php");
    }

  } catch (Exception $e) {

    die("Error".$e->getMessage());

  }

 ?>
    
asked by Diego 02.06.2017 в 20:01
source

1 answer

2

Before contributing a possible solution I want to point out some things about your code.

  • Beware of a poorly configured PDO : For me PDO is the best option when consulting our database. But if the itself is not well configured it could be dangerous. That good configuration implies that at the time of making the connection you set the attribute PDO::ATTR_EMULATE_PREPARES to false ... otherwise you could be a victim of SQL injection , as I explain on the point 2 of this response .

  • Using rowCount is not the best choice for data . Although it is the most popular way to try to know the number of rows in a query, rowCount is not the best option for it . The same PHP Manual says the following:

  •   

    PDOStatement::rowCount() returns the number of rows affected by   the last DELETE, INSERT, or UPDATE statement executed by the   corresponding PDOStatement object.

         

    If the last SQL statement executed by the PDOStatement object   associated was a SELECT statement, some databases could   return the number of rows returned by that statement. But nevertheless,    This behavior is not guaranteed for all databases and should not be relied upon for portable applications.

    Many people seem not to have read that and continue to use rowCount as if it were the panacea.

    In PDO, to know if there is data, you only have to ask for the same data , since the method that asks for the data returns false if there is no data.

    So if you do something like this:

    $datos = $pdo->query("SELECT * FROM table")->fetchAll();
    if ($datos) {
        // Aquí determinas si hay datos ¡no necesitas absolutamente de rowCount()!
    }
    

    If you want to count the number of rows anyway, use a SELECT COUNT(*) , which will return sure and real how many rows there are in that table .

    You can see this interesting article published in PHP Delusions .

    Now I'm going to answer your question

    To store the query results in a variable, the procedure is this:

     $pdo = new PDO(aquí credenciales de conexión);
     $sql = "SELECT ... INSERT ... UPDATE ...";
     $stmt = $pdo->prepare($sql);
     $stmt->bindParam(...); //Si aplica
     $stmt->bindValue(...); //Si aplica
     $stmt->execute(); 
    
     //Para almacenar los datos en una variable
     $arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
     //Leer variable con los datos
     foreach ($arrDatos as $value) {
        echo $value['una-columna-de-la-tabla'];
     }
    

    Note: There are other ways to store the result set, you can check them at PHP Manual .

    Recommendation

    As I said at the beginning, PDO is in my opinion the best option to consult our data.

    The work is considerably facilitated when we have a class dedicated to managing connections and sending queries in a secure manner. If you are interested, you can try this class: PHP-PDO .

    COMPLETE CODE EXAMPLE

    VIEW DEMO IN PHPFIDDLE

    <!-- Para darle estilo a nuestros resultados en pantalla -->
    <style>
        table {
          border-collapse: collapse;
        }
    
        table,th,td {
          border: 1px solid black;
        }
    </style>
    
    <?php
    
    /*Este requiere es propio de phpfiddle, a no usar en nuestro programa*/
    require "util/public_db_info.php";
    
    /*
        *Crear objeto conexión con las credenciales
        *Cambiar los valores por los nuestros
    */
    $pdo = new PDO($dsn, $user_name, $pass_word);
    /*
        *Esta variable se usa para verificar si ocurrió algún error 
        *durante la ejecución del código
        *Escribiremos un código totalmente controlado
    */
    $bolError=false;
    
    /*
        *PRUEBA: Esto es para mostrar los arrays ordenados, 
        *no tendrá importancia para nuestro programa final, 
        *podemos quitarlo, junto con el </pre> del final
    */
    echo "<pre>";
    
    /*Empezamos... iré indicando los diferentes controles que se hacen*/
    
    /*1. Verificamos que el objeto $pdo no sea nulo*/
    if ($pdo){
    
        $strSQL="SELECT * FROM actor_20171002 WHERE actor_sexo=? and actor_id > ?";
        $stmt = $pdo->prepare($strSQL);
    
        /*
            *Estamos aquí ante un aspecto interesante de PDO
            *podemos prescindir de bind_param o de bind_value
            *y pasar los parámetros mediante un array ($arrParams) en el execute
            *IMPORTANTE: Los valores deben estar en el orden en que aparecen en $strSQL
            *en este caso el 1er valor debe ser el filtro para actor_sexo 
            *y el segundo el filtro para actor_id
        */
        $arrParams=array('F',5);
        $stmt ->execute($arrParams);
    
        /*
            *Si no se esperan demasiados datos, podemos usar fetchAll
            *para obtenerlos todos de una vez en una variable
            *si se esperan muchos datos el Manual recomienda iniciar un puntero con fetch
            *y luego ir recorriendo dicho puntero para leer los valores
            *Aquí, $arrDatos será un array asociativo con todo el resultado
        */
        $arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        /*2. Verificamos los datos obtenidos*/
    
        /*
            *En PDO nosotros podemos actuar sobre los mismos datos
            *para hacer verificaciones...
            *por ejemplo aquí, podemos usar $arrDatos para verificar si hay resultados
            *y haciendo count($arrDatos) sabemos cuántos registros hay
        */
        if ($arrDatos)
        {
            echo "SE ENCONTRARON  ".count($arrDatos). " REGISTROS\n";
    
            /*
                *PRUEBA: La línea siguiente es sólo para prueba
                *Podría no ser útil en nuestro programa final
            */
            print_r($arrDatos);    
    
            /*
                *Vamos a usar una forma de presentar los datos
                *la cual puede variar según la necesidad del programador
                *he optado por presentarlos en una tabla
                *se pueden presentar sin tabla, en un formulario, o donde queramos
                *para escribir código "limpio" (sin echo por todas partes)
                *usaremos una variable $tablaHTML a la cual le iremos agregando todo el contenido
            */
            $tablaHTML='<table>';
            $tablaHTML.="<th>ID</th>
                         <th>Nombre</th>
                         <th>Apellido</th>";
    
            foreach ($arrDatos as $row)
            {
                $intId=$row["actor_id"];
                $strNombre=$row["actor_nombre"];
                $strApellido=$row["actor_apellido"];
                $tablaHTML.="<tr>";
                $tablaHTML.="<td>$intId</td>"; 
                $tablaHTML.="<td>$strNombre</td>"; 
                $tablaHTML.="<td>$strApellido</td>"; 
                $tablaHTML.="</tr>";
            }
    
            $tablaHTML.="</table>";
            echo $tablaHTML;
    
            /*Aquí si se desea se puede cerrar $stmt... en PDO no es necesario*/
    
        } else {
    
            /*
                *Este bloque se ejecutará cuando $arrDatos sea false
                *lo cual indicará que hubo un fallo en el $stmt,
                *por eso usamos errorInfo() del $stmt para encontrar el motivo del fallo
                *la variable $bolError declarada más arriba será establecida a true
                *y crearemos un mensaje de error
            */
            $bolError=true;
            $strMensaje="Error en la consulta: ".$stmt->errorInfo()[2];
    
        }
    
        /*Por estar en phpfiddle cerrarmos $pdo, en nuestra aplicación no es obligatorio*/
        $pdo = null;
    
        }else{
    
            /*
                *Este bloque se ejecutará cuando $pdo sea nulo
                *la variable $bolError declarada más arriba será establecida a true
                *y crearemos un mensaje de error
            */              
            $bolError=true;
            $strMensaje="La conexión  es  nula. Verifique sus credenciales o la base de datos";
    
        }
    
        /*
            *Informar sobre algún error:
            *Este bloque evalúa la variable $bolError
            *e informa sobre el error ocurrido, que se encontrará en $strMensaje
        */
    if ($bolError)
    {
        print_r($strMensaje);
    }
    
    /*Cerramos nuestro pre... útil sólo para nuestras pruebas :)*/
    echo "</pre>";
    
    ?>
    

    Result :

    The test print_r throws this:

    SE ENCONTRARON  2 REGISTROS
    Array
    (
        [0] => Array
            (
                [actor_id] => 6
                [actor_nombre] => Jennifer
                [actor_apellido] => Jones
                [actor_sexo] => F
                [last_update] => 2017-10-23 10:08:02
            )
    
        [1] => Array
            (
                [actor_id] => 7
                [actor_nombre] => Holly
                [actor_apellido] => Hunter
                [actor_sexo] => F
                [last_update] => 2017-10-23 10:08:02
            )
    
    )
    

    And the table that we generate with the data is this:

    table {
      border-collapse: collapse;
    }
    
    table,
    th,
    td {
      border: 1px solid black;
    }
    <table>
      <th>ID</th>
      <th>Nombre</th>
      <th>Apellido</th>
      <tr>
        <td>6</td>
        <td>Jennifer</td>
        <td>Jones</td>
      </tr>
      <tr>
        <td>7</td>
        <td>Holly</td>
        <td>Hunter</td>
      </tr>
    </table>
        
    answered by 02.06.2017 / 21:16
    source