PHP 5.4.33 Released

mysqli->affected_rows

mysqli_affected_rows

(PHP 5)

mysqli->affected_rows -- mysqli_affected_rowsRetorna o número de linhas afetadas pela operação MySQL anterior

Descrição

Estilo orientado a objetos (propriedades):

int $affected_rows;

Estilo de procedimento:

int mysqli_affected_rows ( mysqli $link )

mysqli_affected_rows() retorna o número de linhas afetadas pela ultima consulta INSERT, UPDATE, REPLACE ou DELETE associada ao parâmetro link indicado. Se a ultima consulta foi invalida, esta função irá retornar -1.

Para comandos SELECT mysqli_affected_rows() funciona como mysqli_num_rows().

Parâmetros

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Valor Retornado

Um inteiro maior do que zero indica o número de linhas afetadas ou obtidas. Zero indica que nenhum registro foi atualizado por um UPDATE, não foram encontradas linhas em uma claúsula WHERE na consulta ou que a consulta ainda não foi executada. -1 indica que a consulta retornou com erro.

Nota:

Se o número de linhas afetadas for maior do que o maior valor inteiro possível, o número de linhas afetadas será retornado como uma string.

Exemplos

Exemplo #1 Estilo orientado a objeto

<?php
$mysqli 
= new mysqli("localhost""my_user""my_password""world");

/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %s\n"mysqli_connect_error());
    exit();
}

/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n"$mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n"$mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n"$mysqli->affected_rows);

/* select all rows */
$result $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n"$mysqli->affected_rows);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Exemplo #2 Estilo de procedimento

<?php
$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"CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n"mysqli_affected_rows($link));

mysqli_query($link"ALTER TABLE Language ADD Status int default 0");

/* update rows */
mysqli_query($link"UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n"mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link"DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n"mysqli_affected_rows($link));

/* select all rows */
$result mysqli_query($link"SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n"mysqli_affected_rows($link));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link"DROP TABLE Language");

/* close connection */
mysqli_close($link);
?>

O exemplo acima irá imprimir:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

Veja Também

add a note add a note

User Contributed Notes 5 notes

up
6
Anonymous
3 years ago
On "INSERT INTO ON DUPLICATE KEY UPDATE" queries, though one may expect affected_rows to return only 0 or 1 per row on successful queries, it may in fact return 2.

From Mysql manual: "With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated."

See: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Here's the sum breakdown _per row_:
+0: a row wasn't updated or inserted (likely because the row already existed, but no field values were actually changed during the UPDATE)
+1: a row was inserted
+2: a row was updated
up
4
djnigelharkness at yahoo dot com
4 years ago
<?php
    $gHostName   
="localhost";   
   
$gUserName    ="root";
   
$gPassword    ="mypassword";
   
$gDBName     ="dbName";
   
$mysqli = new mysqli($gHostName, $gUserName, $gPassword,    
           
$gDBName);
   
   
$username="username";    $email="user@xxx.edu";
   
$password="3442f6e94a733237a3e844f0286b92f559bf794d";
   
   
//insert
//    $stmt = $mysqli->prepare("INSERT INTO j_user
       
(username,email,password) VALUES (?, ?, ?)");
//   
$stmt->bind_param('sss',$username, $email, $password);
//   
$stmt->execute();
//   
$stmt->close();

    //delete
//   
$stmt = $mysqli->prepare("DELETE FROM j_user WHERE
                        username
=?");
//   
$stmt->bind_param('s',$username);
//   
$stmt->execute();
//   
$stmt->close();

    //update
//   
$stmt = $mysqli->prepare("UPDATE j_user SET email=? WHERE
                        username
='wjw6349'");
//   
$stmt->bind_param('s',$email);
//   
$stmt->execute();
//   
$stmt->close();

    if (
$mysqli->connect_error){
        echo("
Connect failed: ".mysqli_connect_error()); exit();
    }

   
$querySelect = "SELECT * FROM j_user";
   
$resultSet = $mysqli->query($querySelect);
   
    if(
$resultSet->num_rows > 0){
        while(
$row = $resultSet->fetch_assoc()){
            foreach(
$row as $fieldValue){
               
$bigString .= "<em>$fieldValue</em><br />\n";
            }
           
$bigString .= "<hr />";
        }
       
$mysqli->close();
        echo
$bigString;
    }

    function __autoload(
$className) {
        require_once
$className.'.class.php';
    }
    //start the session and create it
    session_start();
   
$_SESSION['name'] = $_POST['username']."_".time();
    //encrypt the password   
    sha1(
$_POST['password']) == $password
    header("
Location:admin.php");
    //check if the session is set
    session_start();
    if (isset(
$_SESSION['name'])) { }
?>
up
3
ric at xpellshop dot com
3 years ago
"Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed."

what if i need to know which one of the three occurred? It's dumb that there is no distinction between the three.
up
1
fastest963 at gmail dot com
3 months ago
empty($db->affected_rows) will return TRUE even if affected_rows is greater than 0. Manually check < 1 if you're looking for failure.
up
-1
oilpc at oilpc dot com
4 years ago
For "INSERT" or "UPDATE" statement for modifying data contained in one row of one table I checked if number of affected rows equals 1 to determine success of the operation. It works fine both for errors and false value of WHERE condition (that might be generated according to specific application user acces privileges).
<?php
if ($mysqli->affected_rows==1){
    echo
"success";
}
else {
    echo
"fail";
}
?>

Checking if mysqli->affected_rows will equal -1 or not is not a good method of determining success of "INSERT IGNORE" statements. Example: Ignoring duplicate key errors while inserting some rows containing data provided by user only if they will match specified unique constraint causes returning of -1 value by mysqli->affected_rows even if rows were inserted. (checked on MySQL 5.0.85 linux and php 5.2.9-2 windows). However mysqli->sqlstate returns no error if statement was executed successfully.
<?php
if ($mysqli->affected_rows!=-1){
    echo
"success";// for "INSERT IGNORE" statements will not occur if there were any duplicate key errors ignored during execution of the query
}
else {
    echo
"fail";// "INSERT IGNORE" statements causing any duplicate key errors (however ignored) lead to mysqli->affected_rows equal -1
}

// Example below works for "INSERT IGNORE" stattements, too
if ($mysqli->sqlstate=="00000"){
    echo
"success";
}
else {
    echo
"fail";
}
?>
To Top