I have some working code to take out the tediousness of binding each variable to its parameter manually in a pdo prepared statement. I loop through the $_POST
array and bind the variables to the params dynamically based on the name attributes from the html form.
My question is, is it safe to do this? Am I open to SQL injection?
Here is my code -
if( !empty($_POST) ){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO planes (name, description) VALUES(:name, :description)");
foreach($_POST as $key => &$value){
$key = ':'.$key;
$stmt->bindParam($key, $value);
}
$stmt->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
}