I have the following insert function. Is it safe from a sql injection. If it isn’t then how do I make it safe.
public function insert($postValues, $table){
$dbh = $this->connect();
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fields = implode(array_keys($postValues), ',');
$values = "'".implode(array_values($postValues), "','")."'";
$insertQuery = 'INSERT INTO '.$table.' ('.$fields.') VALUES (:'.$fields.')';
$stmt = $dbh->prepare($insertQuery);
foreach($postValues as $vals) {
$stmt->execute($vals);
}
$message = $sucessMessage;
}
catch(PDOException $e){
$message = $e->getMessage();
}
$dbh = null;
return $message;
}
Thanks in Advance
If each column type is a
PDO::PARAM_STR, then it is fairly simple to bind your parameters to unamed paramter markers using PDOStatement::execute. However, if the column types vary, then you need to specify the column type for each column when you bind to it with PDOStatement::bindParam.Accepting table and column names from what appears to be user input, is not a good idea. The query will fail if the table or column names are incorrect, but you need to be very careful to ensure that the table and column names are safe to use. The following example checks the table and column names against a whitelist, prior to executing any SQL: