What is the purpose of using prepared statements in PHP for database insertion?

Using prepared statements in PHP for database insertion helps prevent SQL injection attacks by separating SQL logic from user input. Prepared statements also improve performance by allowing the database to compile the SQL query once and execute it multiple times with different parameters. This approach provides a more secure and efficient way to insert data into a database.

// 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', $username);
$stmt->bindParam(':email', $email);

// Set the values of the parameters
$username = "john_doe";
$email = "john_doe@example.com";

// Execute the prepared statement
$stmt->execute();