How can user input be securely handled in PHP when inserting data into a MySQL database?

User input can be securely handled in PHP when inserting data into a MySQL database by using prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating the SQL query from the user input data. By binding parameters to the query, the database engine can distinguish between code and data, ensuring 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 a parameterized statement
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");

// Bind parameters to the query
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);

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