What are some common pitfalls to avoid when retrieving and processing data from a database in PHP?

One common pitfall to avoid when retrieving and processing data from a database in PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely interact with the database.

// Incorrect way without prepared statements
$user_input = $_GET['user_input'];
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = mysqli_query($connection, $query);

// Correct way with prepared statements
$user_input = $_GET['user_input'];
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();
$result = $stmt->get_result();