PHP, how to make mysqli throw exceptions so try/catch will work

I read that I need to do this before I get a mysqli connection to make it throw exceptions:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Open in new window


But it's not working. Here is my sample code of how I'm using it:

try {
                mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

                $mysqli_conn = new mysqli("ZZZlocalhost", $userName, $password, $dbName);
            }
        } catch (Exception $e) {
            echo "It reached the catch block";
        }

Open in new window


Noticed I intentionally put three capital 'Z's before the name 'localhost' to make it bomb out, hoping the echo statement in the catch block would execute, but it isn't.

Can anyone tell me what I'm doing wrong please? Thanks.
elepilAsked:
Who is Participating?
 
Ray PaseurCommented:
Good practices are documented here.  The online PHP man pages do not recommend using Exceptions - they handle MySQLI errors as just that - errors.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Probably the reason that PHP recommends error instead of exception is that once a MySQLI connection has failed, there is really not much more you can do programmatically.  It's usually a fatal condition, not something that is just exceptional and recoverable.  But that said, here is a script that will show you how to get the exceptions into play.  The man page references should be particularly helpful.  The PHP user-contributed notes on some of the pages are wrong - use them only after testing them!
http://iconoun.com/demo/temp_elepil.php

<?php // demo/temp_elepil.php

/**
 * How to use MySQLi and Exception
 *
 * http://dev.mysql.com/doc/
 * http://php.net/manual/en/mysqli.overview.php
 * http://php.net/manual/en/mysqli.constants.php
 * http://php.net/manual/en/mysqli.construct.php
 * http://php.net/manual/en/mysqli.connect-errno.php
 * http://php.net/manual/en/mysqli.connect-error.php
 * http://php.net/manual/en/mysqli.set-charset.php
 *
 * http://php.net/manual/en/language.exceptions.php
 * http://php.net/manual/en/class.exception.php
 * http://php.net/manual/en/class.runtimeexception.php
 * http://php.net/manual/en/class.mysqli-sql-exception.php
 */
error_reporting(E_ALL);
echo '<pre>';


// DELIBERATELY WRONG CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost";
$db_name = "X_main";
$db_user = "X_user";
$db_word = "X_word";


// TELL MYSQLI TO THROW EXCEPTIONS INSTEAD OF REPORTING ERRORS
mysqli_report(MYSQLI_REPORT_STRICT);


// TRY/CATCH (/FINALLY IF PHP >= 5.5)
try
{
    $mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);
	$mysqli->set_charset("utf8mb4");
}
catch (mysqli_sql_exception $e)
{
    // WARNING: DO NOT DO THIS OR YOU WILL EXPOSE YOUR CONNECTION CREDENTIALS!
    // var_dump($e);

    $oops  = '<br>MySQLI Exception Code: ' . $e->getCode();
    $oops .= '<br>MySQLI Exception Msg: '  . $e->getMessage();
    trigger_error($oops, E_USER_WARNING); // MAYBE THIS SHOULD BE _ERROR IF PHP < 5.5
}

/**
 * PHP 5.5+
finally
{
    // TRY REMOVING THIS
    exit;
}
*/


// EXPOSE SOME INTERESTING INFORMATION
var_dump($mysqli);
var_dump($mysqli->get_charset());

Open in new window

HTH, ~Ray
0
 
Marco GasiFreelancerCommented:
I use PDO and I'm not sure you can do it this way with mysqli. I'm sure you can do it in another way:

$mysqli_conn = new mysqli("ZZZlocalhost", $userName, $password, $dbName);

// Check connection
if ($mysqli_conn->connect_error) {
    die("Connection failed: " . $mysqli_conn->connect_error);
} 
echo "Connected successfully";
?>

Open in new window


I got this example from http://www.w3schools.com/php/php_mysql_connect.asp
0
 
Ray PaseurCommented:
Sorry - I should have included this link:
http://php.net/manual/en/mysqli-driver.report-mode.php
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
elepilAuthor Commented:
Marco,

Thanks for responding. The way you did it was the way I was trying to avoid. I wanted mysqli to throw exceptions, but thanks for trying.
0
 
elepilAuthor Commented:
Ray,

I can see you still don't like Exceptions. I'm guessing PHP did not use "throwing Exceptions" early on because this is a concept born out of classic OOP languages (which came a bit after PHP was created). The reason PHP can be an awkward language today is because it was originally a procedural language that, after seeing the success of classic OOP languages, decided to "wanna-be" an OOP language. Instead of redesigning PHP from the ground up at some point, they instead decided to patch in OOP features given their current non-OOP friendly architecture. That's why we have to use $this just to access every single property in a class, which is ludicrous. That's why we use the -> to access a property in a class because PHP insists on still using the '.' as a concatenator. That's why late static binding had to be introduced at some point. It's an old language that has tried so hard to modernize but simultaneously refused to throw out old habits. The only reasons I can see why PHP is so in vogue is:

1) It has a plethora of functions which compensate for its awkwardness, and developers appreciate this enough to put up with the idiosyncrasies of the language.
2) It is quite stable, despite the awkwardness of the language.
3) Big companies use it, which gives the perception to developers that "if it's good enough or them, it's good enough for me"
4) All the above leads to its huge market share, which significantly adds more to attracting developers to it (like me) for employment opportunities.

If your application called a function that called another function and so on, however many levels deep, and it bombed out at the deepest level, how can you handle that error condition without using Exceptions? I've seen your samples before, and you are using die(). That is a horrible way to handle errors.

You said "Probably the reason that PHP recommends error instead of exception is that once a MySQLI connection has failed, there is really not much more you can do programmatically." This is NEVER the case. At the very least, you owe your user a meaningful message and a graceful exit. At times, not recovering could leave you in a messed up state. An example is a MySQL transaction that calls multiple stack levels of functions that fail somewhere. If you don't throw back the Exception to the point of origin, how can you do a rollback? Would you leave your transactions in the middle of some state and just die() out of the application?

Lastly, and people don't usually talk about this, your reputation as a developer banks a lot on how you handle your errors. Imagine using any application that just die()'s when it encounters a problem, as opposed to one that recovers on its feet and brings you back to a predictable state. If you had to pay money, which will you buy?

There is a reason why Exceptions has become the de facto standard in classic OOP languages such as Java, C#, ActionScript and others that use this mechanism. It gives the developer control over WHEN and HOW to handle the error condition. I hope you will get over your aversion towards Exceptions because it is here to stay.
0
 
Ray PaseurCommented:
...use $this just to access every single property in a class, which is ludicrous
You're entitled to your opinion, of course, and there are plenty of people who agree with you.  But there are plenty of OOP languages (JavaScript comes to mind) that use this-> notation  Or prototypal inheritance.  It's not ludicrous - it's perfectly sensible to designate the scope of a variable, and in my experience, the more explicitly you can designate scope, the better off you are. Given the history of PHP and the willingness of the authors to provide backwards compatibility, $this-> makes good sense (the dot had already been used as the concatenation operator).  Every language has its warts - consider JavaScript's use of the plus sign - it does type coercion!  And don't get me started on the assumed semicolon.  The authors of PHP understood that you just can't go and break 50% of the internet because you think everybody else should be doing things differently.  We live in the real world, and it includes a lot of web sites that already work correctly.

It looks like you misunderstood my distinction between getting a connection and using the connection.  If you can't get the connection, you probably can't build the web page at all.  If the server goes away in the middle of a transaction, you have a different problem and you use different techniques to handle that condition.  And when you see my code using die() here at E-E, please understand that I do not have enough time left in my life to teach every novice, one-at-a-time, how to turn PHP errors into ErrorException.  For some reason, PHP seems to be a language that people think they don't need to learn it before they start using it.  Maybe that is why you see so many poor examples of PHP code on the internet.

Also, I would probably not speak out in such absolute terms against PHP error handling unless I really understood it.  The Exception model in PHP is there to make it more familiar to the OOP developers from Java and JavaScript, but the error handlers are far more capable than you give credit.  Again, the addition of Exception was PHP's way of allowing older programming to run alongside newer programming.

For some confirmation-bias reading, try this one.
http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/
0
 
Ray PaseurCommented:
Afterthought.  Not my quote, but I can't remember who said it... "Good programmers can recognize great programming; great programmers can recognize good-enough programming."  Wordpress, which generates 1/4 of all internet traffic, is not great programming, far from it.  But it's definitely good-enough programming!
0
 
elepilAuthor Commented:
But there are plenty of OOP languages (JavaScript comes to mind) that use this-> notation  Or prototypal inheritance.  It's not ludicrous

Ray, you missed my point. I didn't say using 'this' is ludicrous. I said the fact that you have to use $this to access EVERY property within a PHP class, that's the ludicrous part. Even JavaScript does not require you to use 'this' to access EVERY variable within function scope. JavaScript is not a classic OOP language. In fact, JavaScript is just like PHP which at some point decided to go OOP, and it's choice to go the route of prototypal inheritance to effect inheritance is in itself awkward. By comparing PHP and JavaScript, you're comparing two languages which are unorthodox (although I have come to love JavaScript).

And when you see my code using die() here at E-E, please understand that I do not have enough time left in my life to teach every novice, one-at-a-time, how to turn PHP errors into ErrorException

Ray, you are more than just using die() for convenience, you actually promote it. die() is convenient for a developer during the development stage, but it has no place in production.

The Exception model in PHP is there to make it more familiar to the OOP developers from Java and JavaScript, but the error handlers are far more capable than you give credit.

And therein lies the problem, Ray. You actually denigrate the efficacy of Exceptions and diminish it down to an "accommodation" for OOP developers. It is a LOT more than that. If, after everything I said in my prior post, you still think Exceptions are just a "convenience" to make OOP developers "feel at home", then you are still totally missing how Exceptions totally trounce the traditional way PHP handles errors. That's why there is such a thing as a stack trace, it not only gives developers a map of program execution at the time an error occurred, but it is also the basis by which Exceptions are thrown backwards to the starting point of the whole chain.

And as for that link you provided, the author of that article said it well when he said:

because the damage [in PHP] is so systemic

But as I enumerated in my previous post, PHP does have virtues, but certainly not in its design and architecture, but on its enormous functionality due to its age and long-time support from developers. This is not because PHP is such a brilliantly designed language, but rather, because it was the only viable scripting language available to developers for a long time before the advent of classic OOP languages. For developers like me, I don't love PHP, I put up with it, but I don't hate it either because I do see positives, so I'll live with it. You yourself have admitted PHP is quirky and messy.

You know what you should do, Ray? Learn a classic OOP language. Sooner or later, you will be granted an epiphany on what you have been missing.
0
 
elepilAuthor Commented:
Wordpress, which generates 1/4 of all internet traffic, is not great programming, far from it.

Actually I thought WordPress is ingenious. The ingenious part is not because it was written in PHP. It's its design, how it provides hooks comprising of actions and filters for developers to interject their own code. I like how WordPress has a built-in menu utility, really loved that. But more importantly, WordPress is popular because:

1) It was easy for non-developers to hop on and start a blog going;
2) It has so much support in terms of themes and plugins, and their modular nature is once again attractive to non-developers and developers alike;
3) It has gained so much traction that many employers actually require WordPress.

In every sense, WordPress' vogue is similar to PHP. It was a clumsy little thing when it started, and it grew because of the tremendous user support. Take out the user support, and all that's left is clumsy.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.