How can PHP and SQL be effectively integrated to ensure data security and prevent SQL injection attacks?

To ensure data security and prevent SQL injection attacks when integrating PHP and SQL, it is crucial to use prepared statements with parameterized queries. This method helps to separate SQL code from user input, preventing malicious code injection. By binding parameters to placeholders in the SQL query, the database engine can distinguish between code and data, enhancing security.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

// Prepare a SQL query with a parameterized statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the parameter value and execute the query
$username = $_POST['username'];
$stmt->execute();

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the data retrieved from the database
}

// Close the statement and connection
$stmt->close();
$conn->close();
?>