mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rowsObține numărul de rânduri afectate de precedenta operațiune MySQL

Avertizare

Această extensie a devenit învechită în PHP 5.5.0 și a fost eliminată în PHP 7.0.0. În locul ei trebuie utilizată extensia MySQLi sau PDO_MySQL. Accesați de asemenea ghidul MySQL: selectarea unei API și FAQ asociat pentru informații suplimentare. Variante alternative pentru această funcție includ:

Descrierea

mysql_affected_rows ([ resource $link_identifier = NULL ] ) : int

Obține numărul de rânduri afectate de ultima interpelare INSERT, UPDATE, REPLACE sau DELETE asociată cu link_identifier.

Parametri

link_identifier

Conexiunea MySQL. Dacă identificatorul legăturii nu este specificat, se presupune că este ultima legătură deschisă cu ajutorul mysql_connect(). Dacă nu este găsită nici o astfel de legătură, se va încerca crearea uneia prin apelul mysql_connect () fără argumente. În caz că nici o conexiune nu este găsită sau stabilită, se va genera o eroare de nivelul E_WARNING.

Valorile întoarse

Întoarce numărul de rânduri afectate în caz de succes și -1 dacă ultima interpelare a eșuat.

Dacă ultima interpelare a fost o interpelare DELETE fără o clauză WHERE, atunci toate rândurile din tabel au fost eliminate, dar această funcție va întoarce zero în cazul versiunilor MySQL înainte de 4.1.2.

La utilizarea UPDATE, MySQL nu va reînnoi coloanele unde valoarea nouă coincide cu cea veche. Aceasta crează posibilitatea că mysql_affected_rows() nu va coincide cu numărul de rânduri ce se potrivesc condiției de selectare, dar va fi doar numărul de rânduri ce au fost direct afectate de interpelare.

Interpelarea REPLACE întâi elimină înregistrarea cu aceeași cheie primară, apoi inserează noua înregistrare. Această funcție întoarce numărul înregistrărilor eliminate plus numărul înregistrărilor inserate.

În cazul interpelărilor de tip "INSERT ... ON DUPLICATE KEY UPDATE", valoarea întoarsă va fi 1 dacă a fost efectuată inserare, sau 2 dacă a fost actualizat un rând existent.

Exemple

Example #1 Exemplu mysql_affected_rows()

<?php
$link 
mysql_connect('localhost''mysql_user''mysql_password');
if (!
$link) {
    die(
'A eșuat conectarea: ' mysql_error());
}
mysql_select_db('mydb');

/* aceasta ar trebui să întoarcă numerele corecte ale înregistrărilor eliminate */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Înregistrări eliminate: %d\n"mysql_affected_rows());

/* cu o clauză WHERE care nici o dată nu este adevărată, aceasta ar trebui să întoarcă 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Înregistrări eliminate: %d\n"mysql_affected_rows());
?>

Exemplul de mai sus va afișa ceva similar cu:

Înregistrări eliminate: 10
Înregistrări eliminate: 0

Example #2 Exemplu mysql_affected_rows() utilizând tranzacții

<?php
$link 
mysql_connect('localhost''mysql_user''mysql_password');
if (!
$link) {
    die(
'A eșuat conectarea: ' mysql_error());
}
mysql_select_db('mydb');

/* Reînnoiește înregistrările */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Înregistrări reînnoite: %d\n"mysql_affected_rows());
mysql_query("COMMIT");
?>

Exemplul de mai sus va afișa ceva similar cu:

Înregistrări reînnoite: 10

Note

Notă: Tranzacții

Dacă utilizați tranzacții trebuie să apelați mysql_affected_rows() după interpelarea INSERT, UPDATE sau DELETE, și nu după COMMIT.

Notă: Interpelări SELECT

Pentru a căpăta numărul de rânduri întoarse de un SELECT, utilizați mysql_num_rows().

Notă: Cheile externe în cascadă

mysql_affected_rows() nu numără înregistrările afectate implicit prin utilizarea ON DELETE CASCADE și/sau ON UPDATE CASCADE în constrângerile cu chei externe.

A se vedea și

add a note add a note

User Contributed Notes 11 notes

up
3
HMax
16 years ago
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.
up
2
Ome Ko
12 years ago
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];
}
?>
up
1
temp02 at flexis dot com dot br
18 years ago
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.
up
0
dobrys at abv dot bg
16 years ago
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
up
0
deponti A_T tiscalinet D0T it
20 years ago
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)
up
-1
vitospericolato at gmail dot com
7 years ago
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();
up
-1
gtisza at gmail dot com
4 years ago
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.
up
-2
ahmd
7 years ago
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.
up
-3
brian at smitherconsulting dot com
7 years ago
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.
up
-7
steffen at showsource dot dk
19 years ago
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
up
-13
sean at adtools dot co dot uk
15 years ago
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.
To Top