11

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

3
  • 3
    php.net/manual/en/function.mysql-affected-rows.php Commented Dec 2, 2011 at 13:16
  • @AllisonC you should post that as an answer.. :) Commented Dec 2, 2011 at 13:16
  • The warning indicates that the query failed rather than that you are using the wrong function. You should implement proper error handling. Commented Dec 2, 2011 at 13:18

5 Answers 5

15

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).

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for pointing out the corresponding method for Prepared Statements!
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 reference
5

You needs mysql_affected_rows

3 Comments

thanks, but even then i get this error: Warning: mysql_affected_rows(): supplied argument is not a valid MySQL-Link resource
You need to supply mysql_affected_rows with the connection identifier, not the result record, as written on php.net/manual/en/function.mysql-affected-rows.php
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 reference
5

You also may want to use a ROW_COUNT() function, e.g. -

UPDATE table1 SET column1 = 100 WHERE column2 = 10;
SELECT ROW_COUNT();

From the reference - ROW_COUNT() returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE, DELETE, or INSERT...

Comments

3

clamp,

you need to supply a resource to mysql_affected_rows, not a result record. See the links that the others have posted for additional information.

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query($q);
echo mysql_affected_rows($link);

Comments

0

Whe can also do it using PDO :

$db = new PDO('', '', '')// your connection
$sql = "UPDATE tb_table SET rowname = value WHERE rowid = 1";
$query = $db->query($sql);
echo $query;

1 Comment

$sql must be replaced by your own request

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.