Report error while performing UPDATE with SQL

4

I have a project, in which the administrator can change registered data of tables, but if the query is executed but no change occurs, I would like to return a message or error, here is what I have so far:

$altera = "UPDATE z SET y= a WHERE x= x";
$select = mysql_query($altera);
if($select){
   mensagem de sucesso
}else{
   mensagem de erro
}

Variances and things like that are not important, what matters is the if there at the end, which, I think, that if the variable occurs, it will do what is inside the brackets, if it does not, it will show message of error, but this does not work, and I do not know who else to turn to.

    
asked by anonymous 16.11.2015 / 23:20

2 answers

1

This can be done by using the mysql_affected_rows function that returns the number of rows actually affected in the last query using UPDATE .

$altera = "UPDATE z SET y= a WHERE x= x";
$select = mysql_query($altera);
   if($select){
      if(mysql_affected_rows() > 0){
        print "foram atualizadas (". mysql_affected_rows() .") linhas";
      } else {
        print "consulta efetuada, mas nenhuma linha modificada";
      }
   }else{ 
      die("Erro: " . mysql_error());
   }
Regardless of what you want, either if($select) or if(!$select) as a mysql_errno() would have the same impact if it were to verify that this query was executed, with if($select) checking if the returned value was executed ( true ) or ( false ) , mysql_errno() returns the error number of the last operation, if it has failed, just as it does mysql_error() but this returns the error as a numeric value.

For the problem of compatibility with even lower versions, there is the function mysql_numrows() (also discontinued) .

  

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension   should be used. See also MySQL: choosing an API guide and related FAQ   for more information.

In Portuguese documentation this warning is omitted, why I do not know, but it pretty much says mysql_* functions are obsolete , that is, the use of these functions is discouraged from PHP >= 5.5.0 and have been completely removed from PHP >= 7.0.0 .

Alternatively, the following extensions exist:

Some references:

17.11.2015 / 08:42
3

I use this way with Firebird:

if ($query){
    echo "Tudo OK";
}

if (ibase_errmsg()){
    echo "Erro técnico: ".ibase_errmsg();
}

You can do with the function mysql_error() .

  

mysql_error - Returns the text of the previous MySQL operation error message

Example with MySQL with your problem:

  $altera = "UPDATE z SET y= a WHERE x= x";
  $select = mysql_query($altera);

  if($select){
      // tratativa caso for bem-sucedido
  } 

  if (mysql_error()){
      // tratativa caso for mal-sucedido
  }

Note:

MySQL functions that start with mysql_* are deprecated and will be deprecated from PHP 7, consider using mysqli_* .

References:

link

link

    
17.11.2015 / 00:35