What are the potential pitfalls of using the mysqli extension in PHP for MySQL connections?

One potential pitfall of using the mysqli extension in PHP for MySQL connections is the risk of SQL injection if user input is not properly sanitized. To prevent this, always use prepared statements with parameterized queries to securely interact with the database.

// Establish a connection to the database using mysqli
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Use prepared statements with parameterized queries to prevent SQL injection
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "example_username";
$stmt->execute();
$result = $stmt->get_result();

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

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