1

I'm trying to show a message when a fatal error occurs after executing a query to a mysql database. I want to do smthg like that:

 $query="INSERT INTO ...";
 $stmt=$dbc->prepare($query);
 $stmt->bind_param("sdd", $place,$id_user,$id_sem); 
 $success=$stmt->execute();   

 if($success)                                                       
     echo "success";
 else
     echo "error";
                                                               

The problem is that because a fatal error occurs, my program logically crashes, so I can't print nothing just after the line with the execute() function.

I tried to solve this problem with a try/catch statement, but there's no change.

 $query="INSERT INTO ...";
 try{  
   $stmt=$dbc->prepare($query);
   $stmt->bind_param("sdd", $place,$id_user,$id_sem); 
   $success=$stmt->execute();   
 }
 catch(Throwable $e){
   echo "error";
 }

Can someone help me please ?

Thanks !

  • 1
    Could you please add your code that you tried with try/catch. – Karthik Radhakrishnan Jul 23 '20 at 14:23
  • What is the fatal error that you're getting? It's better to try to prevent the fatal error than try to catch it – aynber Jul 23 '20 at 14:29
  • 1
    mysqli errors aren't thrown as exceptions by default. See https://stackoverflow.com/questions/22662488/mysqli-fetch-assoc-expects-parameter-call-to-a-member-function-bind-param for how to enable this. – Barmar Jul 23 '20 at 14:32
  • what fatal error you are talking about? – Your Common Sense Jul 23 '20 at 14:36
  • Thanks @Barmar , the post in your link solved my pb, I used try/catch with the mysql_sql_exception, after doing mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); – CaptainCoding7 Jul 23 '20 at 15:13
  • Out of curiosity, what was the problem? – Barmar Jul 23 '20 at 15:14
  • @Barmar , I am doing a reservation site for events and I was just trying to tell a user in he already reserved his place at a specific event. If he did, a 'duplicate entry for key PRIMARY" error occurs in mysql. That's why I needed to warn the user. – CaptainCoding7 Jul 23 '20 at 15:29
  • However, according to @YourCommonSense in the answer of the subject above, using a try/catch is maybe not the right way to deal with my pb, can you confirm it YourCommonSense ? – CaptainCoding7 Jul 23 '20 at 15:30
  • Yes, for many reasons. the most important one, error reporting is a complex business, it cannot be limited to just blurting out a single word "error". Besides, it just makes no sense to wrap every statement in a distinct try catch. Your program should have uniform and configurable error handler that would handle all errors in a single place. Which means you don't need a try catch right beside the query execution. Read more in my article https://phpdelusions.net/articles/error_reporting – Your Common Sense Jul 23 '20 at 15:39
  • Ok thanks, yes I started to read your great article, and I will read it more carefully. Thx ! – CaptainCoding7 Jul 23 '20 at 15:43

0 Answers0