When I develop with PHP and MySQL[PDO] can I use two try blocks like below?

@mymac1 You don’t need quotes for prepared statements.

I didn’t say error handler is not a good way but also there’s nothing wrong with using try…catch blocks. index.php is just an example, it can be put anywhere else depending on application design, in a framework this might be a framework code that runs controller actions, for example. In a most simplistic micro-framework index.php can be a good place and adding a try…catch block is far from bloating it in my opinion. As far as duplicating code there are other ways to deal with it. Yes, an error handler might be more universal but then we are talking about a specific scenario so your last reply to @Dormilich equally applies to you now.

First, there is nothing so complicated in creating error handling code as you seem to suggest. Sure, you can make it elaborate as much as you can but here we are talking about a simple case of dealing with PDO exceptions.

Second, if you suggest leaving errors alone then you suggest letting php spit out its user-unfriendly error messages or abort silently, neither case being what is usually desired. Then what’s your solution apart from that your solution is no solution?

Third, my high-brow theoretical musings come from working code and it’s really nothing difficult to grasp. And I certainly suggested a reliable and very simple exception handling code - dodn’t you understand what wrapping code in try…catch block means?

Fourth, PHP is not intelligent enough to know what I want to do or show to users when a database error occurs. Therefore, I need to deal with the exceptions, errors, whatever.

Fifth, a little bit of humility would help you communicate better because shouting in condescending manner how your way is the only way does not help at all and doesn’t really testify about your expertise - quite the opposite. Just accept please that you are not an infallible programming god like none of us is.

No, you don’t put any try blocks in your methods. You catch the errors elsewhere and there are different ways of dealing with it.

One possibility is when you have a central php file (like index.php) through which all page requests come through. Then you use a single try...catch (PDOException $e) {...} in that file and you run all your classes from within the try block. Then any PDO errors from your classes will be caught in this one place where you can do what you want to do in such cases, for example display a message about a database error or log the error to a file.

Another method might be not using a try block at all but in your central file, or in a common included file, use set_exception_handler, which you can use to catch any uncaught exceptions in your own exception handler. In this handler you can either do the same thing for any kind of exception, or you can check the kind of exception with the instance of operator to detect PDOException or any other exception.

First, there is nothing so complicated in creating error handling code as you seem to suggest.

No, there is. It IS complicated and in 99% PHP users will do it wrong. The code above is an example.

This IS the point. There is nothing special in PDO exceptions. It always made me wonder, why PHP users are so obsessed with them. They NEVER care to write a dedicated handling code for a permission error but for some reason always elaborate to write one for PDO. But both are just application errors all the same and have to be treated equally. Of course save for the case when you need to catch, but we aren’t discussing this case here.

Your solution

My solution is simple. There is nothing special in database errors. So they have to be treated like any other error. That’s really simple.[quote=“Lemon_Juice, post:22, topic:259383”]
And I certainly suggested a reliable and very simple exception handling code
[/quote]
Come on. The handling is what you are writing inside the catch block. And you didn’t suggest anything.

And what to write there is the question. Most of time people end up with a code which is worse than PHP default action. And only with a considerable effort they can come up with a code that either duplicates PHP functionality or makes a bowl of spaghetti, but at least does no harm.

One really needs to be a pro to write a good handling code. Which is different in different situations. So one should just leave errors alone as long as they have no idea on how to deal with them. Because anything that a noob can think of most of time does severe harm, making an ugly mocking of the PHP default handling action. Don’t you see it in the code from the OP?

For some reason you are taking my suggestions personally, thinking I am telling you what to do. But I am clearly discussing the code and the situation for the certain topic where is nothing much to discuss, really. As long as the guy have not a slightest idea in the error handling, he ought to leave PDO exceptions alone. By doing so, he will have perfect code to deal with by the time he will have an idea on the error reporting. But if he will start it now, he will do a severe harm that will take a lot of time to refactor.

See, you are accusing me of suggesting a silent abort. But imagine that error is not database related, but, say, an error from a require statement. You can’t catch it. So you have to do something else. But the point is, whatever you’ll do will affect database errors as well without the need to treat them any specifically. This is the bloody point.

Writing error handlers is a distinct topic, orthogonal to the current question. The job of the database code is to throw an error. How it will be handled is another question. All the OP have to do is not to try to handle them on the spot. So he just have to leave PDO exceptions alone.

1 Like

See. All you are doing in the catch block is echoing the error out. But the thing is, PHP already can do it and in a much better form.

So why bother?

Whether equally or not equally depends on the requirements. Sometimes, an almost equal treatment is required, for example a different message is displayed to the user, all other things being equal.[quote=“colshrapnel, post:24, topic:259383”]
My solution is simple. There is nothing special in database errors. So they have to be treated like any other error. That’s really simple.
[/quote]
Simple or not, looking at the code from the OP it is almost certain he is not handling any errors at all so if you tell him not to do anything about database errors then he will continue not handling any errors. If you have a simple solution for handling errors then please share it instead of saying to not do anything.

Of course, what I suggested what only the basic idea, I didn’t go into details because I don’t even know if the OP is interested in it at all. Besides, as you also mentioned, this is a little off topic here so I don’t want to go into the details if the OP doesn’t explicitly ask for them.

It is not about you telling me what to do but about you telling others not to do anything implying they will not understand it, anyway. If you know how to handle errors in a good way, as you seem to suggest here, then please share it and we will all learn something. The OP clearly used all those PDOException catch blocks for a reason - because he wanted to achieve something, namely useful messages shown in the browser. Instead of telling him to forget about the idea it would be much more useful to show how to do it in a proper way.

I think we may have gone too far with this discussion as it doesn’t seem to bring forth anything constructive to this topic.

Sorry, I thought it’s quite obvious: what the OP wants can be seen from his code: it’s simply displaying an error message. While I thought you are aware of the fact that an uncaught exception will be shown all the samе.

So by leaving exceptions alone he will have his useful error messages shown in the browser first class.

Words ‘useful’ and ‘first class’ are very relative in this case. They are anything but useful or first class for normal users visiting a web site - they hardly understand them and they look ugly. They are useful for programmers - but web sites are not only for programmers.

Stop.
I can tolerate anything but hypocrisy.

One message before you did care for the OP wishes only:

The OP clearly used all those PDOException catch blocks for a reason - because he wanted to achieve something, namely useful messages shown in the browser.

And I showed you that leaving exceptions alone will fulfill them 100%. This should have put an end to any discussion.
Words ‘useful’ and ‘first class’ address the exact code from the OP, without any “related” or vague speculations.

And what does a “normal user” see in a browser is a bloody different topic, absolutely irrelevant to PDO and exceptions.
If you have no idea how to prevent a site user from seeing PHP errors in the browser, you can ask it in a distinct topic. I’ll be delighted to explain.

There’s northing contradictory in what I wrote before and catering to the wishes of the OP and normal users are not exclusive things. The world is not black or white, either or, etc. But I see you are on a crusade to prove some superior vague idea of yours so you are right that I should stop this discussion.

The idea of the error reporting is vague for PHP users only. For the rest of the world it is crystal clear and as simple as an egg.

  1. On a dev server PHP errors are shown on screen
  2. On a live server PHP errors are logged while a generalized apology page is shown.

Both these rules are common for all PHP errors and PDOExceptions are not an exception.
If this schoolbook stuff is too vague for you it is anything but my problem.

You clearly don’t get what I wrote or deliberately don’t want to. It is your ideas that are vague because you are communicating them in a vague manner and instead of simply explaining them clearly you are writing stuff like this above - what’s this supposed to achieve other than probably boost your ego?

Again, what’s this supposed to do other than make you feel superior? Who gains what reading this kind of stuff coming from you?

At least finally you’ve managed to write something sensible. Keep up the good work!

I think this thread has run its course and if moderators visit here I suggest to close it since my debate with @colshrapnel here doesn’t make sense any more.

1 Like

This “sensible” stuff is irrelevant to the question asked.
While the relevant answer for the OP has been given long time ago: for the code present there should be not a single try catch.

You hijacked this question with your irrelevant questions and now asking mods to close it. How nice.

Fairly certain the hijacking was a co-op effort here (or maybe 3 or more), but nonetheless, I’m not really happy with closing topics purely because two people have two different views on a subject and banter back and forth on it. However, I do agree that this seems to have gone beyond what was needing to be discussed and is getting a tad bit repetative.

With all that said, I’d love this to stay open as maybe the OP still has some lingering questions and I’d like to encourage everyone to look to their needs, whether it means they need/want to handle PDO exceptions in a specific way or whether they want/need to handle all exceptions in a global way. As I believe that is the next point in contention and whatever the OP decides is best for them, should be reasonable enough to continue through that path (despite our own opinions on the matter).

6 Likes

this will catch errors in PDO constructor…? note: only one try catch block… constructor called from another method…

private function banned_user() {

        $username = $this->username;

        try {

            $conn = $this->dbConn() ;

            $q = "SELECT * FROM banned_users WHERE username=?";
            $stmt1 = $conn->prepare($q);
            $stmt1->execute([$username]);
            $result = $stmt1->setFetchMode(PDO::FETCH_ASSOC);
            $bannedData = $stmt1->fetchAll();
            if (count($bannedData) == 0) {
                // no records found
                return false;
            } else {
                $conn = null;
                return true;
            }
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

    // Connect to DB method
    private function dbConn() {

            // Connect to DB
            $conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
            // set the PDO error mode to exception
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            return $this->conn;

    }

Why do you want to catch PDO errors?

I know, you have no idea. But at least try to think for the first time, why do you want it

because according to php.net manual - somewhere i saw but forgot where if you do not catch and construction PDO(…) FAILS may reveal all database credentials…now clear?

To prevent leaking database credentials, as well as other sensitive information, you should configure PHP properly.

To do that you should set display_errors ini setting to off.

It will prevent all leakage once for all and you won’t need to hassle with every single exception

2 Likes

but if wanted a script test in production…? after offer it to users… ?

On a live site you should log errors instead of displaying them. So you will see every error in the error log.

Therefore set log_errors to on and then take a peek into the error log.

Remember that nobody should see site errors. This is why your echo $e->getMessage is harmful. At the same time, once error occurred to a site user, you will have no idea it happened. While if you have errors logged, you can always have an idea what is going on.

2 Likes