Jump to content



Photo

Using Oop For Mysqli Connection, Can'T Redirect


  • Please log in to reply
3 replies to this topic

#1 Lou

Lou

    Advanced Member

  • Members
  • PipPipPip
  • 97 posts

Posted 9 March 2012 - 12:54 PM

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");
}

  • 0

#2 Lou

Lou

    Advanced Member

  • Members
  • PipPipPip
  • 97 posts

Posted 9 March 2012 - 1:18 PM

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;
}
?>

  • 0

#3 rob

rob

    Advanced Member

  • Members
  • PipPipPip
  • 138 posts

Posted 9 March 2012 - 1:22 PM

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/m...i.construct.php
  • 0

#4 Lou

Lou

    Advanced Member

  • Members
  • PipPipPip
  • 97 posts

Posted 9 March 2012 - 1:30 PM

thanks rob, still getting used to oop.
  • 0