What are common pitfalls when retrieving data from a MySQL database using PHP?

One common pitfall when retrieving data from a MySQL database using PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To solve this issue, always use prepared statements with parameterized queries to prevent SQL injection.

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

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

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

// Get the result set
$result = $stmt->get_result();

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

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