With php/mysql how can i get the number of rows that a query affected?
what i tried so far:
$result = mysql_query($q);
mysql_num_rows($result);
but it says that Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource
The affected_rows / mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.
mysql_affected_rows() may be called immediately after executing a statement with mysql_real_query() or mysql_query() . It returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE , DELETE , or INSERT . For SELECT statements, mysql_affected_rows() works like mysql_num_rows() .
Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all. Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row. However and on the rare occasion, >0 is required where this has also happened to me before; that is the reason of my answer.
MySQL ROW_COUNT() can be used to get the total number of rows affected by MySQL query. To illustrate it we are creating a procedure with the help of which we can insert records in a table and it will show us how many rows have been affected.
if you're using PDO (wich i would recommend), for a direct query exec()
returns the number of affected rows. for Prepared Statements theres a method called rowCount()
.
if you're using the mysql-functions, there's mysql_affected_rows()
.
EDIT:
seems like you're using the mysql-functions. mysql_num_rows
, wich is what you're using, returns the length of your result set (for SELECT-Statements for example). what you need to use is mysql_affected_rows
(as already said).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With