What are potential pitfalls to avoid when working with mysqli in PHP?

One potential pitfall to avoid when working with mysqli in PHP is not properly sanitizing user input, which can leave your application vulnerable to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely interact with your database.

// Example of using prepared statements with mysqli to avoid SQL injection

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

// Prepare a statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$username = $_POST['username'];
$stmt->bind_param("s", $username);

// Execute the query
$stmt->execute();

// Bind the results to variables
$stmt->bind_result($result);

// Fetch the results
$stmt->fetch();

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