Solved

PHP Redirect on Database Connection Error

Posted on 2012-03-12
4
393 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
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…
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 …

828 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