There are no rows affected by an update with identical data.
So here is one very ugly solution for these cases:
<?
function mysql_matched_rows() {
$_kaBoom=explode(' ',mysql_info());
return $_kaBoom[2];
}
?>
(PHP 4, PHP 5)
mysql_affected_rows — 최근 MySQL 작업으로 변경된 행 개수를 얻음
$link_identifier
] )
link_identifier
에 마지막 INSERT, UPDATE, REPLACE,
DELETE 질의로 영향받은 행 수를 얻습니다.
link_identifier
MySQL
연결. 지정하지 않으면 mysql_connect()로 연 마지막 연결을
사용합니다. 연결이 없으면, 인수 없이 mysql_connect()를
호출하여 연결을 만듭니다. 연결이 성립되지 않으면
E_WARNING
등급의 오류를
생성합니다.
최근 질의가 실패했을 경우 -1을 반환하고, 그렇지 않을 경우 적용된 행의 개수를 반환한다.
최근 질의가 WHERE 절이 없는 DELETE 질의일 경우 테이블의 모든 레코드가 삭제되지만, 4.1.2 버전 이후의 MySQL은 0을 반환한다.
UPDATE를 사용할 때, MySQL은 기존 값과 새로운 값이 동일한 컬럼들은 변경하지 않을 것이다. mysql_affected_rows()는 조건에 해당하는 행의 개수가 아닌 실제 변경된 행의 개수를 제공한다.
REPLACE 구문은 동일한 기본키의 레코드를 먼저 삭제한 다음 새 레코드를 삽입한다. 결국, 이 함수는 삽입된 레코드수와 삭제된 레코드수를 더한 값을 반환한다.
Example #1 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('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>
위 예제의 출력 예시:
Records deleted: 10 Records deleted: 0
Example #2 트랜젝션을 이용한 mysql_affected_rows() 예제
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>
위 예제의 출력 예시:
Updated Records: 10
Note: 트랜젝션 사용
트랜젝션을 사용한다면 mysql_affected_rows()는 COMMIT 명령 이후가 아니라 INSERT, UPDATE, DELETE 명령 직후에 호출해야 한다.
Note: SELECT 구문
SELECT에 의해 반환된 행의 수를 얻기 위해서는 mysql_num_rows()를 사용하면 된다.
There are no rows affected by an update with identical data.
So here is one very ugly solution for these cases:
<?
function mysql_matched_rows() {
$_kaBoom=explode(' ',mysql_info());
return $_kaBoom[2];
}
?>
SCENARIO
1. You're using MySQL 4.1x with foreign keys.
2. You have table t2 linked to table t1 by a CASCADE ON DELETE foreign key.
3. t2 has a UNIQUE key so that duplicate records are unacceptable.
3. You have a REPLACE query on t1 followed by an INSERT query on t2 and expect the second query to fail if there's an attempted insert of a duplicate record.
PROBLEM
You notice that the second query is not failing as you had expected even though the record being inserted is an exact duplicate of a record previously inserted.
CAUSE
When the first query (the REPLACE query) deletes a record from t1 in the first stage of the REPLACE operation, it cascades the delete to the record that would be duplicated in t2. The second query then does not fail because the "duplicate" record is no longer a duplicate, as the original one has just been deleted.
I was just testing "INSERT INTO ... ON DUPLICATE KEY UPDATE" syntax, on PHP 5.3.29 and mysql_affected_rows() was returning either 2 for updated row, 1 for inserted new row, and also 0, which was not documented, evidently when nothing was inserted. I was inserting a single row.
If you use "INSERT INTO ... ON DUPLICATE KEY UPDATE" syntax, mysql_affected_rows() will return you 2 if the UPDATE was made (just as it does with the "REPLACE INTO" syntax) and 1 if the INSERT was.
So if you use one SQL request to insert several rows at a time, and some are inserted, some are just updated, you won't get the real count.
I see that when try to use mysql_affected_rows() with "mysql_pconnect(...)" without link indetifier as param in "mysql_affected_rows()" the result is allways -1.
When use link identifier "mysql_affected_rows($this_sql_connection)" - everything is Fine. This is is on PHP Version 5.2.0
Hope that this was helpfull for somebody
It works also for REPLACE query,returning:
0 if the record it's already updated (0 record modified),
1 if the record it's new (1 record inserted),
2 if the record it's updated (2 operations: 1 deletion+ 1 insertion)
Note that when the CLIENT_FOUND_ROWS connection flag was used, affected_rows returns the number of rows matched by the WHERE condition of an UPDATE query, even if the query doesn't actually change those rows. I.e. for
INSERT INTO t(id, val) VALUES (1, 'x');
UPDATE t SET val = 'x' WHERE id = 1;
the number of affected rows will be 0 normally but 1 with CLIENT_FOUND_ROWS.
calling mysql_affected_rows(null)
is not the same that calling mysql_affected_rows()
So, if you have a $link variable that could be null, you must write
if($link)
$n=mysql_affected_rows($link);
else
$n=mysql_affected_rows();
In the case of INSERT where a row/slot had been previously deleted, making an uncollapsed hole in the table, and the record being inserted fills that empty row/slot, that is to say, the inserted data did not create a new row/slot/space, then this may explain why a zero result is returned by this function.
Using OPTIMIZE TABLE will also return true.
So, if you want to check the numbers of deleted records, use mysql_affected_rows() before OPTIMIZE TABLE
Here's a little function I've been using for a while now, pass it two parameters (action command (1 or 0 see notes)) and a sql statement.
It returns a simple line which shows the length of time taken to action the query, the status of the query (0= query not actioned, you can set this value for testing, 1=success qry executed successfully, -1= failed, there was a problem with the sql statement) the number of lines affected by that query and the sql statement itself.
I've found this invaluable when trying to tie down large amounts of updates to a table, using this you can easily see where a query was successfully executed and the number of rows are affected, or where there are problems and a statement has failed for example.
<?php
function dosql($action,$sql){
# assuming you have setup a link to your database entitled $link
# action = 1 run this query
# action = 0 don't run, just return sql statement
$start = getmtime();
if($action==1){
$result = mysql_query($sql);
$affectedrows = "[".mysql_affected_rows($link)."]";
}
return "[".number_format((getmtime()-$start),3)."][$action]: $sql\n";
mysql_free_result($result);
}
?>
Example output:
[0.072][1][80]: UPDATE MYTABLE SET FIELD = 1;
[0.106][1][758]: UPDATE ANOTHERTABLE SET FIELD = 2;
[0.006][-1][0]: UPDATER ANOTHERTABLE SET FIELD = 2;
The output shows:
[Timetaken][result]][lines affected]
The result will be either -1, 0 or 1, -1 means there's a problem with the sql statement, 1 means it executed correctly, 0 means it wasn't executed.