Alex Rivera | Logout

Count How Many Rows Inserted From Last SQL Query

Asked 2012-09-27T14:32:48.473
10

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?

Edit
Report

1 Answer

3

Here are some possibilities:

» If you have an AUTO_INCREMENT column, you can fetch the row number before and after insert

» SELECT ROW_COUNT() returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE, DELETE, or INSERT (doc)

» You can use mysqli_affected_rows (since mysql_ functions are being deprecated) to get the number of affected rows in a previous MySQL operation (doc)

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
mysqli_query($link, "INSERT INTO myTable VALUES (1)");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));
answered 2012-09-27T15:07:58.673

Your Answer