There are 3 ways you can do this the right way, using with Prepared statement:
- passing as parameter:
$sth->bindParam(':param', $param);
- passing as value:
$sth->bindValue(':value', $value)
- 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();
}
Using PDO is the safest way to connect to a PHP BD? in this question have the examples of how to use correctly
– rray