Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Lou

Using Oop For Mysqli Connection, Can'T Redirect

Recommended Posts

Hello again,

I'm converting to mysqli OOP for connecting to my MySQL database. Previously I was using procedural mysqli. Basically, if I a connection can't be made to MYSQLI, I have a handle_error function that takes a user error message and a system error message and then uses the header redirect to my show_error page. I start the session in the config file, which is required on every page. It works when using procedural mysqli.

 

However I can't get it to redirect using MYSQLI objects. It just shows me a white page with the system error message when it can't connect to MYSQL, like it's throwing an exception. I thought only PDO threw exceptions? I must be missing something simple, but I haven't been able to figure it out. Any help would be appreciated.

 

<?php
require_once('./config.php');
$connection = new mysqli(HOST, USER, PASS, DB);
if ($connection == NULL){
handle_error('Message One', 'Message Two');
} else {
 return $connection;
}
?>

 

And the handle_error function in my config file:

 

function handle_error($user_error_message, $system_error_message){ //handle all errors with this function
$_SESSION['user_error_message'] = $user_error_message;
$_SESSION['system_error_message'] = $system_error_message;
header("Location: ./show_error.php");
}

Share this post


Link to post
Share on other sites

This always happens. I spend a few hours trying to solve a problem, post on here, then figure it out. Why does the solution below work with OOP but not what I posted above?

 

<?php
require_once('./config.php');
$connection = new mysqli(HOST, USER, PASS, DB);
if (mysqli_connect_error()){
handle_error('Message One', 'Message Two');
 break;
} else {
 return $connection;
}
?>

Share this post


Link to post
Share on other sites

In your script you're testing a mysqli object ($connection) to NULL; from the manual:

 

OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.

 

http://www.php.net/manual/en/mysqli.construct.php

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×