Question

Just a quick question. Say a call a method like so

mysql_pconnect("server","tator_w","password")
               or die("Unable to connect to SQL server");

Can I have the 'die' call a method rather then display a text message? If so, how?

Was it helpful?

Solution

You would be better off using an if statement rather than relying on short-circuit evaluation if you want to do anything more complicated, e.g.:

if (!mysql_pconnect("server","tator_w","password")) {
    call_a_function();
    //some other stuff
    die(); //if you still want to die
}

OTHER TIPS

register_shutdown_function()

It lets you register a function that will be called when the system exits. Then you can simply die() or exit() without a parameter, which will call your method.

(you may also find set_error_handler() interesting, if slightly unrelated)

Well, not exactly, but you just do

if(!mysql_pconnect("server","tator_w","password")) {
    $some_obj->some_method();
    exit(1);
}

Why not just put in a function call that returns a string?


function myDieFunction()
{
     // do some stuff

     return("I died!");
}

die(myDieFunction());

Or you could try the register shutdown function

Another (but not so nice) way:

mysql_pconnect("server","tator_w","password")
    or foo() & bar() & die("Unable to connect to SQL server");

Note the binary operator & instead of a boolean operator to have all the functions called.

Not being able to connect to the database is probably a severe problem - I consider it a prime target for the use of exceptions.

If you are not able to connect to the database the problem probably needs to be handled delicately, and you probably want to log something about what went wrong, and where it went wrong to be able to make your code better to avoid the problem in the future.

Just a quick sketch up a way to use exceptions.

file view_cart.php

<?php
try
{
    require_once('bootstrap.php');
    require_once('cart.php');

    require('header.php');


    // Get the items in the cart from database
    $items = Cart::getItems();

    // Display them to the user
    foreach ($items as $item)
    {
        echo $item->name.', '$item->price.'<br />';
    }
}
catch (Exception $e)
{
    // Log the exception, it will contain useful info like
    // the call stack (functions run, paramaters sent to them etc)
    Log::LogException($e);

    // Tell the user something nice about what happened
    header('Location: technical_problem.html');
}

require('footer.php');

file bootstrap.php

<?php
$result = mysql_pconnect("server", "tator_w", "password");
if ($result === false)
{
    throw new Exception('Failed to connect to database');
}

// Select database
// Setup user session
// Etc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top