PDO, I did not return results

0

It's been a while since I touched mysql, for various reasons I had to do it I have a file of tests, when I execute my consula in phpmyadmin it works and returns data, if I place the query in a stored procedure it returns data, but I should not use stored procedure, I do not know what to do in the file to execute, now that I go up now I removed the ? ,? and replace them with the user and password but still without results.

I would greatly appreciate your help. Thank you in advance.

Session file

<?php 
include("conexion.php");
class Sesion
{
    function login($user, $password)
    {
        $newconex = new DataBase();

        $quo="  SELECT U._ID AS '_ID',  
                    TRIM(CONCAT(P.NOMBRE,' ',P.APELLIDO)) AS 'NOMBRE' 
                FROM 'usuarios' U, 'personas' P
                WHERE P._ID=U._ID_PERSONA 
                AND U.USUARIO='admin'
                AND U.'CONTRASEÑA'=SHA1('admin');"; 

        $parametros = array($user,$password);
        $resultado = $newconex->query($quo,$parametros);


        $newconex=null;
        if($resultado)
        {
            session_start();//inicia la sesion

            $_SESSION['UCREA'] =$resultado[0]['_ID'];
            $_SESSION['NOMBRE'] =$resultado[0]['NOMBRE'];               
            return 1;               
        }
        else
        {
            return 0;
        }
    }
}?>

DB Class

<?php
    ini_set('display_errors', 'On');
    error_reporting(E_ALL | E_STRICT);

    /* clase de base da datos */
    class DataBase {

        private $conexion = null;

        /* Construcctor */
        public function __construct()
        {
            $HOST = "localhost";
            $DBNAME = "test";
            $USERNAME = "root";
            $PASSWORD = "";
            try {
                $this->conexion = new PDO("mysql:host=".$HOST.";dbname=".$DBNAME, $USERNAME, $PASSWORD);
            } catch (PDOException $e) {
                echo $e->getMessage();
            }
        }

        public function desconectar() 
        {
            if($this->conexion != null) $this->conexion = null;
        }


        public function query($sql,$parametros)
        {
            $make = $this->conexion->prepare($sql);

            if(is_array($parametros))
            {
                $make->execute($parametros);                    
            }
            else
            {
                $make->execute();
            }       


            $result = $make->fetchall();
            $make->closeCursor();
            return $result;
        }

        public function query_exec($sql,$parametros)
        {
            $make = $this->conexion->prepare($sql);

            if(is_array($parametros))
            {
                $result = $make->execute($parametros);  
            }
            else
            {
                $result = $make->execute();
            }
            $make->closeCursor();
            return $result;
        }
    }
?>

Execution file

<?php
    include("class/sesion.php");
    $sesion =new Sesion();
    echo  $sesion->login("admin","admin");
?>

As annotations I want to emphasize that if I do a simple select like

Select 'something' as 'value';

I get results, if I delete the where I get results ... if I use consultation in a stored procedure I get results ... the details is that I can not use it, because it is necessary to see the code in php

/////////// APPENDIX STORED PROCEDURE

DELIMITER //
CREATE PROCEDURE CHECK_SESION(IN username VARCHAR(255),IN userpassword VARCHAR(255))
 BEGIN

     SELECT U._ID AS '_ID', TRIM(CONCAT(P.NOMBRE,' ',P.APELLIDO)) AS 'NOMBRE' 
    FROM 'usuarios' U, 'personas' P
    WHERE P._ID=U._ID_PERSONA 
    AND U.USUARIO=username
    AND U.'CONTRASEÑA'=SHA1(userpassword);

 END //
DELIMITER ;
    
asked by Darkeniel 14.11.2016 в 10:33
source

3 answers

0

If we analyze the code of the store Process:

START TRANSACTION;
SELECT U._ID AS '_ID',  
  TRIM(CONCAT(P.NOMBRE,' ',P.APELLIDO)) AS 'NOMBRE' 
  FROM 'usuarios' U, 'personas' P
  WHERE P._ID=U._ID_PERSONA 
  AND U.USUARIO='admin'
  AND U.'CONTRASEÑA'=SHA1('admin');
IF @@error_count > 0 THEN
  ROLLBACK;
ELSE
  COMMIT;
END;

We can clearly see that it is composed of a total of 3 actions: start trans. a select and depending on whether it gave an error or not, commit or rollback;

  

What you are trying to do will not work in the same way, since it is not the way you should do it.

     

When you use PDO , you must make use of the methods that you provide .

     

It is also clear that it is totally unnecessary to start a transaction for a SELECT

A possible solution to your problem using PDO , would be the following:

function login($user, $pass)
{
    $newconex = new DataBase();
    $query="SELECT U._ID AS _ID,
        TRIM(CONCAT(P.NOMBRE,' ',P.APELLIDO)) AS NOMBRE
      FROM usuarios U, personas P
      WHERE P._ID = U._ID_PERSONA 
        AND U.USUARIO = :user
        AND U.CONTRASEÑA = SHA1(:pass)"; 

    // las claves del arreglo deben empezar con :
    $params = array(
      ':user'=> $user,
      ':pass'=> $pass
    );

    // NOTA 1
    $res= $newconex->query($query,$params);
    $newconex=null;

    // Si no es FALSE y tiene exactamente 1 registro
    if($res && count($res) === 1) {
        session_start();//inicia la sesion

        $_SESSION['UCREA'] =$res[0]['_ID'];
        $_SESSION['NOMBRE'] =$res[0]['NOMBRE'];               
        return 1;               
    } else {
        return 0;
    }
}
  

NOTE 1 : PDOStatement :: fetchAll () returns an array which contains all the remaining rows of the result set. An empty array is returned if there are zero results to obtain, or FALSE in case of failure .   (Personally I would return PDOStatement instead of fetchAll result)

Finally, if you need to use transactions, I recommend you to see PDO :: beginTransaction , < a href="http://php.net/manual/en/pdo.commit.php"> PDO :: commit and PDO :: rollBack

// UPDATE

  • Error: The keys should start with ":" (I forgot)

    $params = array(
       ':user'=> $user,
       ':pass'=> $pass
    );
    
  • Modification: Indicates the charset to the DB (eg:; charset = UTF8)

    $this->conexion = new PDO("mysql:host=".$HOST.";dbname=".$DBNAME.";charset=UTF8", $USERNAME, $PASSWORD);
    
  

To avoid problems with special characters and string comparisons, it is always necessary to indicate the charset in the DSN.

    
answered by 14.11.2016 / 16:22
source
0

Haber, the problem is that you have not read the official documentation on what should be done to make your code work for you. We go in parts ...

// prepare() retorna un PDOStatement y lo asigna a $make.
$make = $this->conexion->prepare($sql);

[...]

// Si bien, completas correctamente el metodo execute(), debes realizar
// antes un par de procedimientos..
$make->execute($parametros);

The official documentation of execute () clearly states:

  

If it included parameter markers, you should:

     
  • call PDOStatement :: bindParam () and / or PDOStatement :: bindValue () for   link variables or values (respectively) to the markers of   parameters. The linked variables pass their value as input and   receive the exit value, if any, of their markers   associated parameters

  •   
  • or pass an array of input-only parameter values

  •   

What I can not find in your code is that bindees the parameters. If your intention was to want to pass parameters, then your error is here:

SELECT U._ID AS '_ID',  
TRIM(CONCAT(P.NOMBRE,' ',P.APELLIDO)) AS 'NOMBRE' 
FROM 'usuarios' U, 'personas' P
WHERE P._ID=U._ID_PERSONA 
AND U.USUARIO='admin' -- En vez de 'admin', deberia ser ':user'
AND U.'CONTRASEÑA'=SHA1('admin'); -- En vez de 'admin', deberia ser ':pass'

and when you pass the values by array, it should be an associative array. Something like:

$parametros = array(
    ":user" => "AcaVaElValor",
    ":pass" => "AcaVaLaContrasenia"
);
    
answered by 14.11.2016 в 15:19
0

Try reviewing the data contained in the $ result variable by modifying your Class Session code:

<?php 
include("conexion.php");
class Sesion
{
    function login($user, $password)
    {
        $newconex = new DataBase();

        $quo="  SELECT U._ID AS '_ID',  
                    TRIM(CONCAT(P.NOMBRE,' ',P.APELLIDO)) AS 'NOMBRE' 
                FROM 'usuarios' U, 'personas' P
                WHERE P._ID=U._ID_PERSONA 
                AND U.USUARIO='admin'
                AND U.'CONTRASEÑA'=SHA1('admin');"; 

        $parametros = array($user,$password);
        $resultado = $newconex->query($quo,$parametros);

        echo"<pre>";
        print_r($resultado);
        echo"</pre>";
        die();

        $newconex=null;
        if($resultado)
        {
            session_start();//inicia la sesion

            $_SESSION['UCREA'] =$resultado[0]['_ID'];
            $_SESSION['NOMBRE'] =$resultado[0]['NOMBRE'];               
            return 1;               
        }
        else
        {
            return 0;
        }
    }
}?>

If the variable $ result is empty, then change your query to the following one, which should bring all the records that are in the table users and people:

$quo="  SELECT U._ID AS '_ID',  
        TRIM(CONCAT(P.NOMBRE,' ',P.APELLIDO)) AS 'NOMBRE' 
        FROM 'usuarios' U, 'personas' P
        WHERE P._ID=U._ID_PERSONA;";

If you obtain data with this modification, it could be that the problem is in how the password was encrypted when entering it in the database.

    
answered by 15.11.2016 в 06:56