1

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;
}
kiko carisse
  • 1,634
  • 19
  • 21

1 Answers1

1

Yes, it's safe. If you're using parameterized queries, you won't be vulnerable to injection attacks.

That being said, it seems that you're reinventing the wheel here, which is most often not the right way to do things. However; that's outside the scope of your question.

Also please see this very similar question where the accepted answer has this to say:

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

catbadger
  • 1,662
  • 2
  • 18
  • 27