What are common pitfalls when using PHP to interact with a MySQL database?

One common pitfall when using PHP to interact with a MySQL database is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements or parameterized queries to securely pass user input to the database.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

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

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

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