Lizza Lizza - 2 years ago 80
MySQL Question

How can I know if my mysql_query update didn't actually update anything?

I am doing an update to a table for a row that may not exist. If it doesn't exist, I need to do an insert. I was initially planning on knowing that I needed to do an insert based on a negative return value from the update statement, but it isn't returning anything negative.

How can I know that the update didn't do anything? Do another query seeing if anything is there? Or maybe a query before?


Answer Source


Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier.

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());

/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());

/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());

If you're using mysqli instead of mysql (mysql was deprecated a long time ago), it's mysqli_affected_rows.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download