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

0

4 Answers 4

11

How about:

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


mysql_query($sql) or customDie("/error");
Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.