What is the difference between mysql_affected_rows and mysql_num_rows in PHP and when should each be used?

The main difference between mysql_affected_rows and mysql_num_rows in PHP is that mysql_affected_rows returns the number of rows affected by the last INSERT, UPDATE, or DELETE query, while mysql_num_rows returns the number of rows in a result set. If you are performing an INSERT, UPDATE, or DELETE query and you want to know how many rows were affected by that query, you should use mysql_affected_rows. On the other hand, if you are retrieving data from a SELECT query and you want to know the number of rows in the result set, you should use mysql_num_rows.

// Example of using mysql_affected_rows
$query = "DELETE FROM users WHERE id = 1";
$result = mysql_query($query);
$affected_rows = mysql_affected_rows();
echo "Number of rows affected: " . $affected_rows;

// Example of using mysql_num_rows
$query = "SELECT * FROM users";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
echo "Number of rows in result set: " . $num_rows;