What are best practices for handling SQL injections in PHP scripts?

SQL injections occur when a malicious user inputs SQL code into a form field, which can manipulate the database query and potentially access or modify sensitive data. To prevent SQL injections in PHP scripts, it is essential to use prepared statements and parameterized queries when interacting with the database.

// Example of using prepared statements to prevent SQL injections
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Using prepared statements to insert data
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);

// Set parameters and execute
$username = "john_doe";
$password = "password123";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();