Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

PHP Redirect on Database Connection Error

Posted on 2012-03-12
4
Medium Priority
?
462 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 15

Assisted Solution

by:Ess Kay
Ess Kay earned 1000 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 111

Accepted Solution

by:
Ray Paseur earned 1000 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 111

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

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Question has a verified solution.

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

When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

610 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