PHP MySQL Error Handling

A simple question (hopefully).

I am currently using the following code:

mysql_query($sql) or header("Location: /error");

To avoid the rest of the script, I need to add exit;or die(). Is there a way to do this using the inline approach as above, or do I need to use:

$result = mysql_query($sql);
if (!result) {
    header("Location: /error");
    exit();
}

thank

+3
source share
4 answers

What about:

function customDie($location) {
    header('Location: ' . $location);
    exit();
}


mysql_query($sql) or customDie("/error");
+11
source

If you insist on doing something this way, it's best to create your own query method that handles all of this. Sort of

function custom_mysql_query($query) {
  $doDebug=true; // Set to true when developing and false when you are deploying for real.

  $result=mysql_query($query);
  if(!$result) {
    if($doDebug) {
       // We are debugging so show some nice error output
       echo "Query failed\n<br><b>$query</b>\n";
       echo mysql_error(); // (Is that not the name)
     }
     else {
      // Might want an error message to the user here.
     }
     exit();
  }
}

custom_mysql_query mysql_query, , , $debug - , , , .

: mysql_query , (, , ). . ( sql)

pdo mysql_ (Google , ).

+6

, MySQL. , - :

$result = mysql_query($sql);
$error = mysql_error() != '' ? true : false;

/* fancy code */

if($error)
{
     header(location: url);
     exit;
}

. , , , :

if(mysql_error() != '')
{
     header();
     exit;
}
+1
$db = mysql_connect(//database info);

$result = mysql_query(//query);
if (mysql_error($db) != '')
{
  header("Location: /error");
  exit();
}

If there is no error after completing the request, the code will continue. Otherwise, the user is redirected and the code stops execution.

0
source

Source: https://habr.com/ru/post/1773650/


All Articles