Correct way to send values through PDO

Asked

Viewed 62 times

1

I was informed that I was doing it incorrectly, the phrase said was the following: "It does no good to use a newer API and keep the vices of the old mysql_*, you should not pass the values directly in the SQL statement, pass separated using the placeholders to make the connection." And I took it as a constructive criticism and 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 right way to accomplish this action?

1 answer

2


There are 3 ways you can do this the right way, using with Prepared statement:

  1. passing as parameter: $sth->bindParam(':param', $param);
  2. passing as value: $sth->bindValue(':value', $value)
  3. passing as array() direct on the run: $sth->execute(array('param'=>$param))

Either way will already avoid SQL Injection. To make an insert, you can make these forms:

EXAMPLE 1:

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:

 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();
 } 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.