What are common pitfalls when using mysql_fetch_assoc in PHP and how can they be avoided?
One common pitfall when using mysql_fetch_assoc in PHP is forgetting to check if the result set is empty before trying to fetch rows. This can lead to errors when trying to access non-existent rows. To avoid this, always check if there are rows to fetch before attempting to fetch them.
// Check if there are rows to fetch before fetching them
$result = mysql_query("SELECT * FROM table");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// Process the fetched row
}
} else {
echo "No rows found";
}