3

Simple question (I hope).

At the moment I am using the following code:

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

To prevent the rest of the script running I need to add exit; or die(). Is there any way to do that using the inline approach as above or do I need to use:

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

Thanks

hdvianna
  • 443
  • 5
  • 13
lethalMango
  • 4,433
  • 13
  • 54
  • 92

4 Answers4

11

How about:

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


mysql_query($sql) or customDie("/error");
Fosco
  • 38,138
  • 7
  • 87
  • 101
6

If you insist on doing things this way it is better to make a custom query method which handles all this. Something like

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();
  }
}

Then just call custom_mysql_query instead of mysql_query then you will always die if a query fails and if $debug is true, you will also get the query which failed and the database error.

But really: You should NEVER use mysql_query or functions which call it(Such as the one I just wrote). It is far too unsafe to ever be used. (Far too difficult to avoid sql injections)

Use the pdo classes instead of the mysql_ methods(Google it, there are many tutorials and explanations online).

Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65
MTilsted
  • 5,425
  • 9
  • 44
  • 76
1

You could check if there was a MySQL error. If you need to do the check later do something like:

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

/* fancy code */

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

Edit: I misread your question and now see that you want to kill it if there's an error so you could just do:

if(mysql_error() != '')
{
     header();
     exit;
}
Gazillion
  • 4,822
  • 11
  • 42
  • 59
0
$db = mysql_connect(//database info);

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

If there isn't an error after the query completes, the code continues. Otherwise, the user is redirected and the code stops executing.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144