How can PHP developers prevent SQL injection when using INSERT INTO queries?

To prevent SQL injection when using INSERT INTO queries in PHP, developers should use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, developers can ensure that user input is treated as data rather than executable code.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL query with placeholders for user input
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");

// Bind parameters to placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);

// Set values for parameters
$username = $_POST['username'];
$email = $_POST['email'];

// Execute the query
$stmt->execute();