Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count How Many Rows Inserted From Last SQL Query

Tags:

mysql

I have this query :

INSERT INTO db1.outbox (DestinationNumber, TextDecoded)
SELECT User.CellPhone, '$SMSMessage' as TextDecoded
FROM db2.User
WHERE User.PurchaseDate BETWEEN 2012-01-01 AND 2012-01-31

it does multiple rows insertion to 'outbox' table. but I don't know how many rows inserted. how to have number of rows inserted from that SQL syntax? thanks.

update I got '-1' as result of this command :

$insertedRows = mysql_query("SELECT ROW_COUNT()");
$rowInserted = mysql_fetch_array($insertedRows);
$rowInserted = $rowInserted[0];
echo $rowInserted;

but I see there are 27 rows inserted on my table. what did I do wrong?

like image 339
Saint Robson Avatar asked Sep 27 '12 14:09

Saint Robson


People also ask

How can I count the number of rows inserted in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do you get the number of rows affected by a query?

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.

What is select @@ rowcount?

Usage. SQL Server @@ROWCOUNT is a system variable that is used to return the number of rows that are affected by the last executed statement in the batch.


1 Answers

put this on your last statement;

SELECT ROW_COUNT();

UPDATE 1

how about using mysql_affected_rows, example

<?php

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

   /* this should return the correct numbers of deleted records */
   mysql_query('you SQL QUERY HERE');
   printf("Records deleted: %d\n", mysql_affected_rows());

?>
like image 88
John Woo Avatar answered Sep 30 '22 12:09

John Woo