How can I replace $ _SESSION with a prepared query?

2

Well here with a doubt, I currently have querys where I ask for information and at the end a clause WHERE where I ask for that information about the id of the current session, that is only the active user at that moment, and I want to adopt a Query prepared because having the variable $_SESSION makes me too vulnerable to sql injections.

This is what I currently have:

if(isset($_GET['id_user'])){
sql "SELECT nombre, apellidos, edad FROM users WHERE id  = '".$_GET['id_user']'";
}

What I want is this:

sql = "SELECT nombre, apellidos, edad FROM users WHERE id = ?";
$id = $_POST['id'];
$stmt=$mysqli->prepare($sql);

if ($stmt) {        
    $stmt->bind_param("i", $id);
    $stmt->execute();

    $Resultado = get_result($stmt);        
    while ($row = array_shift($Resultado)) {

    }

}

But I do not understand how the query will only take the user id of the current session:

Would you understand that this id =? in this line you specify that you only select the data of that user in specific?

I hope and someone can help me with this problem

Thank you all.

    
asked by Noctis 01.08.2018 в 04:10
source

1 answer

3

Your code is fine, except for some spelling errors and logic ...

Let me explain:

  • Here sql the% sign is missing $
  • The while is not necessary if you use get_result . . If you need while , really get_result does not work as fetchAll of PDO. Anyway I will show an easier way to get an associative array. Be careful, get_result will not work if you do not have mysqlnd installed.

Everything else is as you say, I correct the code and explain in comments:

/*
   (a) Aquí, ?  es un marcador de posición, es como si le dijeras
   "ahí va un dato, luego te digo qué dato es, para que no me hagan trampa
*/
$sql = "SELECT nombre, apellidos, edad FROM users WHERE id = ?";
/*
   Aquí lo importante es que $id  tiene que ser tu dato real, 
   no sé si se encuentra en la clave id  de POST o en la clave 
   id_user  de GET, eso depende de ti  ...
*/
$id = $_POST['id'];  //o bien $_GET['id_user']
$stmt=$mysqli->prepare($sql);

if ($stmt) {  
    /*
       (b) Aquí se indica lo que se prometió en (a), o sea
           se le pasa el dato a la API para que lo revise, vea
           que no hay trampa y si no la hay, ejecute la consulta
           esto y el prepare son el núcleo de la protección contra inyección SQL
           La "i"  indica que es un dato de tipo (i)nteger
    */      
    $stmt->bind_param("i", $id);
    $stmt->execute();

    /*El while no es necesario, porque get_result ya te devuelve un array con los datos*/
    $Resultado = get_result($stmt);        
    $arrDatos=array();
    while ($row = $Resultado->fetch_assoc())
    {
            $arrDatos[]=$row;
    }
    /*Aquí dispones de $arrDatos como un array asociativo de resultados*/
    var_dump($arrDatos);   
}
    
answered by 01.08.2018 / 04:33
source