How can one prevent SQL injection vulnerabilities when inserting values directly into SQL queries in PHP?
SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries instead of directly inserting values into SQL queries. This approach ensures that user input is treated as data rather than executable code, making it impossible for attackers to inject malicious SQL commands.
// Establish a connection to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
// Bind the parameters with user input
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// Execute the statement
$stmt->execute();