Number of rows changed by the user

1

I have some tables in a system and for all entries I do the validation and compare if the input is equal to what is currently defined in the table and I use PHP rowCount () to check if I had update and display the correct message for the user.

If I do not compare the input value to the table value and run the update, I will certainly display an error message to the user, since the value being set and the new input being equal, SQL does not execute the update.

Is there any SQL parameter, or parameterization, that allows me to perform the upgrade, even though it is the same as the one currently defined, so that I eternally avoid this comparison of the input with what is currently defined?

    
asked by anonymous 22.10.2015 / 21:48

1 answer

1

You can use the mysqli_affected_rows function that returns the number of rows that have changed.

Table :

+----+----------+--------------------+
| id | nome     | email              |
+----+----------+--------------------+
|  1 | Laerte   | [email protected]   |
|  2 | Ana      | [email protected]      |
+----+----------+--------------------+

Script :

<?php
    $conexao = mysqli_connect("servidor", "usuario", "senha", "banco");

    if (!$conexao) {
        printf("Não foi possível conectar ao banco. Erro: %s\n", mysqli_connect_error());
        exit();
    }

    /* UPDATE com valores iguais */
    mysqli_query($conexao, "UPDATE contatos SET nome = 'Laerte', email = '[email protected]' WHERE id = 1");
    printf("# de linhas alteradas: %d\n", mysqli_affected_rows($conexao));

    /* UPDATE com um valor igual e outro diferente. */
    mysqli_query($conexao, "UPDATE contatos SET nome = 'Laerte', email = '[email protected]' WHERE id = 1");
    printf("<br># de linhas alteradas: %d\n", mysqli_affected_rows($conexao));

    mysqli_close($conexao);
?>

Output :

# de linhas alteradas: 0
# de linhas alteradas: 1

This function returns the Changed Rows , as seen in the console output:

  

mysql > UPDATE contacts SET name = 'Laerte', email = '[email protected]'   WHERE id = 1; Query OK, 0 rows affected (0.03 sec) Rows matched: 1   Changed: 0 Warnings: 0

     

mysql > UPDATE contacts SET name = 'Laerte', email =   '[email protected]' WHERE id = 1; Query OK, 1 row affected (0.04   sec) Rows matched: 1 Changed: 1 Warnings: 0

Reference: mysqli_affected_rows

    
23.10.2015 / 19:42