How can PHP scripts be secured against SQL injections when inserting data into a database?

To secure PHP scripts against SQL injections when inserting data into a database, developers should use prepared statements with parameterized queries. This method separates SQL code from user input, preventing malicious SQL queries from being executed.

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

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

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

// Set parameters and execute query
$username = "JohnDoe";
$email = "johndoe@example.com";
$stmt->execute();