I've been reading about preventing sql injections and seen using prepared statements might help.
I have the following function in a class for crud that I have developed:
public function inserir($tabela, $campos, $dados) {
try {
$campos = implode(", ", $campos);
$dados = implode(", ", $dados);
$sql = $this->pdo->prepare("INSERT INTO " .$tabela. " (" .$campos. ") VALUES (" .$dados. ")");
return $sql->execute();
} catch (PDOException $e) {
echo "Ocorreu um erro: " .$e->getMessage();
}
}
And to use it just do as in the example below:
$teste = array("nome", "sobrenome", "email");
$testeR = array("'Igor'", "'Teste'", "'[email protected]'");
$bd -> inserir("tabela", $teste, $testeR);
And it works correctly.
However, I would like to use bindValue
, but I do not know how to proceed.
The only "idea" I have is that I'll have to make a foreach for each item, but I really have no idea how I'll do it. How to do it right?
Thanks!
EDITED
I modified some things according to the answer below (from @ray) and my code looks like this:
In class:
public function inserir($tabela, $dados) {
try {
$campos = implode(", ", array_keys($dados));
$valores = implode(", ", array_values($dados));
$totalInterrogacoes = count($dados);
$interrogacoes = str_repeat("?,", $totalInterrogacoes);
$interrogacoes = substr($interrogacoes, 0, -1); // remove a última virgula
$sql = $this->pdo->prepare("INSERT INTO " .$tabela. " (" .$campos. ") VALUES (" .$interrogacoes. ")");
var_dump($sql);
//return $sql->execute();
} catch (PDOException $e) {
echo "Ocorreu um erro: " .$e->getMessage();
}
}
And in another test file:
$teste = array("nome" => "Igor", "sobrenome" => "Teste", "email" => "[email protected]");
$bd -> inserir("tabela", $teste);
Then it works correctly, and var_dump($sql)
returns the following:
object (PDOStatement) # 3 (1) { ["queryString"] = > string (58) "INSERT INTO table (name, surname, email) VALUES (?,?,?)" }
However, now the big question arises again: How to make bindValue
of each question for its respective value?