Correct way to send values through PDO [duplicate]

1

I was informed that I was doing incorrectly, the sentence said was as follows: "It's no use to use a newer API and maintain the old vices of mysql_* , you should not pass the values directly in the SQL statement, pass them apart using placeholders to join. " And I took it as a constructive criticism and I would like to know more about this way of passing values, I usually use it as follows:

$pdo=conectar();
$inserirregistro=$pdo->prepare("INSERT INTO tabela(coluna1,coluna2,coluna3,coluna4) VALUES ("valor1", "valor2", "valor3", "valor4")");
$inserirpedido->execute();

What would be the correct way to do this?

    
asked by anonymous 18.12.2015 / 13:25

1 answer

2

There are 3 ways you can do this procedure correctly, using prepared statement :

  
  • passing as a parameter:    $ sth-> bindParam (': param', $ param);
  •   
  • passing as value:    $ sth-> bindValue (': value', $ value)
  •   
  • passing as array() direct in execute:    $ sth-> execute (array ('param' = > $ param))
  •   

    Either way will already prevent SQL Injection . To do an insert, you can do the following:

    EXAMPLE 1: < RTI ID = 0.0 >
    try {
    
        $dbh = new PDO('mysql:host=localhost;dbname=SeuBanco', $usuario, $senha);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    
        $sth = $dbh->prepare("INSERT INTO tabela(coluna1,coluna2,coluna3,coluna4) VALUES (:valor1, :valor2, :valor3, :valor4);");
    
        $valor1 = 'exemplo de valor 1';
        $valor2 = 'exemplo de valor 2';
        $valor3 = 'exemplo de valor 3';
        $valor4 = 'exemplo de valor 4';
    
        $sth->bindParam(':valor1', $valor1);
        $sth->bindParam(':valor2', $valor2);
        $sth->bindParam(':valor3', $valor3);
        $sth->bindParam(':valor4', $valor4);
    
        $sth->execute();
    
    } catch (PDOException $e) {
       echo 'Erro: ' . $e->getMessage();
    } 
    

    EXAMPLE 2: < RTI ID = 0.0 >
     try {
    
         $dbh = new PDO('mysql:host=localhost;dbname=SeuBanco', $usuario, $senha);
         $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    
         $sth = $dbh->prepare("INSERT INTO tabela(coluna1,coluna2,coluna3,coluna4) VALUES (:valor1, :valor2, :valor3, :valor4);");
    
         $data = array(
                     'valor1' => 'exemplo de valor 1',
                     'valor2' => 'exemplo de valor 2',
                     'valor3' => 'exemplo de valor 3',
                     'valor4' => 'exemplo de valor 4'
                );
    
         $sth->execute($data);
    
     } catch (PDOException $e) {
           echo 'Erro: ' . $e->getMessage();
     } 
    
        
    18.12.2015 / 14:01