How can SQL injection vulnerabilities be prevented in PHP when querying a database?

SQL injection vulnerabilities can be prevented in PHP when querying a database by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable code, reducing the risk of SQL injection attacks.

// Establish a database connection
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

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

// Bind parameters and execute the query
$username = $_POST['username'];
$stmt->bind_param('s', $username);
$stmt->execute();

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

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