Search code examples
phpmysql

Can SQL tell me how many row(s) were updated?


I would use only a single query:

$sql = "UPDATE gallery SET order = (order+1) WHERE id_categ = ".$id;
$res = mysql_query($sql);

...

Is it possible?


Solution

  • mysql_affected_rows()

    mysql_affected_rows — Get number of affected rows in previous MySQL operation

    Example:

    $sql = "UPDATE gallery SET order = (order+1) WHERE id_categ = ".$id;
    $res = mysql_query($sql);
    printf("Affected rows: %d\n", mysql_affected_rows());
    

    Note that the mysql_affected_rows() return you the affected rows whether updated/deleted of your last run query. For example:

    $sql = "UPDATE gallery SET order = (order+1) WHERE id_categ = ".$id;
    $res = mysql_query($sql);
    
    $sql = "UPDATE gallery2 SET order = (order+1) WHERE id_categ = ".$id;
    $res = mysql_query($sql);
    

    Now if you do:

    printf("Affected rows: %d\n", mysql_affected_rows());
    

    It will return the affected rows for the last query that is gallery2 table's query.

    More Info: