MySQL 计算从上次 SQL 查询插入的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12623778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count How Many Rows Inserted From Last SQL Query
提问by Saint Robson
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.
它对“发件箱”表进行多行插入。但我不知道插入了多少行。如何从该 SQL 语法插入行数?谢谢。
updateI got '-1' as result of this command :
更新我得到'-1'作为这个命令的结果:
$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?
但我看到我的桌子上插入了 27 行。我做错了什么?
回答by John Woo
put this on your last statement;
把它放在你最后的陈述中;
SELECT ROW_COUNT();
UPDATE 1
更新 1
how about using mysql_affected_rows
, example
如何使用mysql_affected_rows
,例如
<?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());
?>
回答by Kermit
Here are some possibilities:
这里有一些可能性:
» If you have an AUTO_INCREMENT
column, you can fetch the row number before and after insert
» 如果你有一AUTO_INCREMENT
列,你可以在插入前后获取行号
» 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)
»SELECT ROW_COUNT()
返回最后一条语句更改、删除或插入的行数,如果它是UPDATE
, DELETE
, 或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)
» 您可以使用mysqli_affected_rows
(因为mysql_
函数已被弃用)获取先前 MySQL 操作 ( 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));