How can PHP developers ensure security and avoid SQL injection vulnerabilities when connecting to databases?

To ensure security and avoid SQL injection vulnerabilities when connecting to databases in PHP, developers should use prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious SQL injection attacks.

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

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

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

// Set parameters and execute the statement
$username = $_POST['username'];
$stmt->execute();

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process each row
}

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