Solved

PHP Redirect on Database Connection Error

Posted on 2012-03-12
4
389 Views
Last Modified: 2012-03-13
I'm new to PHP - after doing a lot of ASP and I'm stumbling on a few issues.
The first issue I have is redirecting to a new page during error handling.

I have the following code:

<?php
session_start();
$error_text = $_SESSION['dberror'];
include 'inc/dbconnect.php';
include 'inc/session_handle.php';
?>

dbconnect.php establishes the connection to the database.
If there's an error, I'd like to redirect to a friendly error page, since the code can't continue.

my dbconnect.php page looks like this:
<?php
$conn = mysql_connect("localjost","root");  //misspelled to trigger error
if (!$conn)
  {
  $_SESSION['dberror'] = mysql_error();
 
        /* Redirect browser */
      header("Location: dberror.php");
      exit;
  }
 
$dbname = 'myown_db';
mysql_select_db($dbname);
?>

This is the result I get:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'localjost' (1) in /Applications/XAMPP/xamppfiles/htdocs/mysite/inc/dbconnect.php on line 3

Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/mysite/inc/dbconnect.php:3) in /Applications/XAMPP/xamppfiles/htdocs/mysite/inc/dbconnect.php on line 9

In ASP this was pretty easy to code.  i could redirect people to however many pages I needed to based on what error was triggered.  It doesn't appear that I can do that in PHP.
(or, at least it appears I need to do it in a much different way.)

Any help you can provide would be appreciated.

Thanks!!!
0
Comment
Question by:slightlyoff
  • 2
4 Comments
 
LVL 15

Assisted Solution

by:Ess Kay
Ess Kay earned 250 total points
ID: 37710320
this site has a veriety of examples for you

http://www.ozzu.com/programming-forum/php-redirect-new-page-from-statement-t59426.html


hope this helps



<?php
 
if( $something ){
 
   Header("Location: somewhere.php");
 
} else {
 
   Header("Location: <!-- m --><span class="postlink">http://www.google.com</span><!-- m -->");
 
}
 
?>

Open in new window



 
if (conditiona) {
 
include ('page_a');
 
}
 
else {
 
include ('page_b');
 
]
 
 
 
 

Open in new window



 
if($flag == 'blabla')
 
   print "<script language="Javascript">document.location.href='page_a.php' ;</script>";
 
else
 
   print "<script language="Javascript">document.location.href='page_b.php' ;</script>";
 
 

Open in new window





best one


if($flag == "something") {
 echo "<meta http-equiv=\"refresh\" content=\"0;URL=page_1.php\">";
} else {
 echo "<meta http-equiv=\"refresh\" content=\"0;URL=page_2.php\">";
}
0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 37712140
Usually you want to use localhost instead of localjost ;-)
This scripts shows some of the basics in PHP and MySQL.
<?php // RAY_mysql_example.php
error_reporting(E_ALL);


// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQL
// MAN PAGE: http://php.net/manual/en/ref.mysql.php
// MAN PAGE: http://php.net/manual/en/mysql.installation.php
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
// MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
// MAN PAGE: http://php.net/manual/en/function.mysql-query.php
// MAN PAGE: http://php.net/manual/en/function.mysql-errno.php
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php
// MAN PAGE: http://php.net/manual/en/function.mysql-num-rows.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-array.php
// MAN PAGE: http://php.net/manual/en/function.mysql-insert-id.php



// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";


// OPEN A CONNECTION TO THE DATA BASE SERVER
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF THE SCRIPT GETS THIS FAR IT CAN DO QUERIES




// ESCAPE AN EXTERNAL DATA FIELD FOR USE IN MYSQL QUERIES
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, SHOW THE ERROR
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS




// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = mysql_num_rows($res);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/>$sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $num ROWS OF DATA ";
    echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
while ($row = mysql_fetch_assoc($res))
{
    var_dump($row);
}




// A WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// GET THE RESULTS SET ROW IN AN ARRAY WITH A NUMERIC INDEX - POSITION ZERO IS THE COUNT
$row = mysql_fetch_array($res, MYSQL_NUM);
$num = $row[0];
$fmt = number_format($num);
echo "<br/>THERE ARE $fmt ROWS IN THE TABLE";




// MAKING AN INSERT QUERY AND TESTING THE RESULTS
$sql = "INSERT INTO my_table (username) VALUES ('$safe_username')";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
$id  = mysql_insert_id($db_connection);
echo "<br/>YOU JUST INSERTED A RECORD WITH AUTO_INCREMENT ID = $id";

Open in new window

Here is a modified version (untested but valid in principle) that will collect the error messages and redirect the client browser to a new URL, sending the error messages in the GET argument.
<?php // RAY_mysql_example.php
error_reporting(E_ALL);


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";


// START THE OUTPUT BUFFERS
ob_start();

// OPEN A CONNECTION TO THE DATA BASE SERVER
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
}

// GET THE OUTPUT BUFFERS
$buf = ob_get_clean();

// IF THERE IS ANYTHING IN THE BUFFERS, IT IS AN ERROR MESSAGE
if ($buf)
{
    $url = 'http://path/to/error_handler.php?q=' . urlencode($buf);
    header("Location: $url);
    exit;
}
// IF THE SCRIPT GETS THIS FAR IT CAN DO QUERIES

Open in new window

With your ASP background, you would breeze through this book.  It will help you get a grip on the syntax differences between ASP and PHP.
http://www.sitepoint.com/books/phpmysql4/

HTH, ~Ray
0
 
LVL 1

Author Closing Comment

by:slightlyoff
ID: 37714818
Thank you both for your help!
There are a lot of things I like about PHP - and although I dabbled in ASP.NET, it seems PHP does what I need.  If I can get around the strange things :)

Thanks for the link - I'll read up on that!
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 37715594
Thanks for the points.  You'll love the SitePoint book.  Very readable with great examples. ~Ray
0

Featured Post

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question