Solved

PHP Redirect on Database Connection Error

Posted on 2012-03-12
4
377 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
Comment Utility
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 108

Accepted Solution

by:
Ray Paseur earned 250 total points
Comment Utility
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
Comment Utility
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 108

Expert Comment

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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

728 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now