Difference between query () and execute () [duplicate]

2

It really is the same:

$base->query("DELETE FROM EJ_TABLA WHERE ID='$Id'");

What to do this:

$base->prepare("DELETE FROM EJ_TABLA WHERE ID='$Id'")->execute();

?

    
asked by Mario G. Lucas 21.08.2018 в 14:26
source

2 answers

3
  

When we use the mysqli or PDO interfaces; we can work   the queries of the following modes

  • query() When we do not need our query to execute dynamic data; that is, the user will not send variables that will intervene to send the desired result
  • EXAMPLE

    $data = $conexion->query("SELECT * FROM posts");
    
  • execute() At the moment we need our system to respond to process queries with dynamic data that the user sends in the form of variables; it is necessary to use prepared statements to try to avoid SQL injection attacks
  •   

    PDO EXAMPLE

    $id = 9;
    $data = $conexion->prepare("SELECT * FROM posts WHERE id = :id");
    $data->execute([":id" => $id]);
    $resultado = $data->fetch(PDO_FETCH_ASSOC);
    
      

    MYSQLI EXAMPLE

    $id = 12;
    $data = $conexion->prepare("SELECT * FROM posts WHERE id = ?");
    $data->bind_param("i", $id);
    $data->execute();
    
      

    In either case mysqli or PDO at the time of use   prepared sentences; we need to make use of: name markers    :nombre or placeholders ? to indicate the data   dynamics that are going to be processed in the query

        
    answered by 21.08.2018 / 15:02
    source
    4

    The way you are using it, yes, the result is the same.

    BUT! No, they are not and they do not work exactly the same.

    Prepared sentences serve to avoid the SQL injection automatically escaping the linked parameters and at the same time" optimize "the query if it needs to be done repeatedly.

    Suppose the following case:

    <?php
    // CUIDADO: esto elimina la tabla EJ_TABLA 
    $Id = "1'; DROP TABLE EJ_TABLA; SELECT * FROM EJ_TABLA WHERE ID='1";
    
    // El resultado de hacer
    $base->query("DELETE FROM EJ_TABLA WHERE ID='$Id'");
    
    // Seria equivalente a
    $base->query("DELETE FROM EJ_TABLA WHERE ID='1'; DROP TABLE EJ_TABLA; SELECT * FROM EJ_TABLA WHERE ID='1'");
    
    // Lo cual claramente no es el resultado esperado
    
    //----------
    
    // En cambio si se usa correctamente (y suponiendo que estas usando MySQLi)
    $stmt = $base->prepare("DELETE FROM EJ_TABLA WHERE ID=?");
    $stmt->bind_param('s', $Id);
    $stmt->execute();
    
    // Seria equivalente a 
    
    $base->prepare("DELETE FROM EJ_TABLA WHERE ID='1\'; DROP TABLE EJ_TABLA; SELECT * FROM EJ_TABLA WHERE ID=\'1'")->execute();
    
    // Si prestas atención, las comillas fueron escapadas, 
    // se evito la inyección SQL y nada malo habrá pasado.
    
        
    answered by 21.08.2018 в 15:05