Problems with bindValue

1

I have a doubt when using bindValue, I do not link the value of the variable to the sign placed in the query. I leave the code; I hope you can help me

<?php

    $pdo = new \PDO('sqlite::memory:', null, null);

    $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
    $error = false;
    $crearTabla = "CREATE TABLE IF NOT EXISTS usuarios ('usuario' STRING NULL, 'password' STRING NULL,'email' STRING NULL)";
    try{
        $pdo->prepare($crearTabla)->execute();
        echo "Tabla Creada\n";
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
    $insertarUsuario = "INSERT INTO usuarios (usuario,password,email) VALUES ('Matias','yopassword','[email protected]')";
    try{
        $pdo->prepare($insertarUsuario)->execute();
        echo "Usuario Insertado \n";
    }catch(PDOException $e){
        echo "Error al insertar el usuario \n".$e->getMessage();
        $error = true;
    }
    if (!$error) {
        $columna = 'usuario';
        $consulta = 'SELECT ? FROM usuarios';
        $stm = $pdo->prepare($consulta);
        $stm->bindValue(1,'usuario', PDO::PARAM_STR); 
        $stm->execute();
        $data = $stm->fetchAll(PDO::FETCH_OBJ);
        echo "Datos".json_encode($data[0]);
    }
    
asked by Matias 15.03.2018 в 11:17
source

1 answer

0

It seems to me that the PHP Manual does not say this explicitly anywhere, which is a documentation hole in it ... the truth is that prepared queries are for passing values, not for pass column or table names as you try to do.

The reason is clear: this would not do any good, because what prepared queries do is to protect against the injection of code through of the values of the columns, not through the names from the same. From an objective point of view, this query: SELECT usuario FROM usuarios does not have any danger from the point of view of security.

If you want to control the columns / tables that can be consulted, what you can do is create a white list of allowed columns / tables and compare if they are within that list, but do not use queries prepared for it, because < That's not its purpose.

Sources of reference

answered by 15.03.2018 / 12:24
source