What are the best practices for handling data from forms in PHP to avoid SQL injection vulnerabilities?
To avoid SQL injection vulnerabilities when handling data from forms in PHP, it is important to use prepared statements with parameterized queries. This helps to separate the SQL query logic from the user input, preventing malicious SQL code from being executed. Additionally, input validation and sanitization should be performed to ensure that only expected data types and formats are accepted.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
// Execute the prepared statement
$stmt->execute();