What are the best practices for sanitizing user input before inserting it into a database in PHP?
When inserting user input into a database in PHP, it is important to sanitize the input to prevent SQL injection attacks. One of the best practices for sanitizing user input is to use prepared statements with parameterized queries. This helps to separate the data from the query, making it impossible for an attacker to inject malicious SQL code.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize user input using prepared statements
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->execute();