Home > OS >  How to display less content of connection error in php
How to display less content of connection error in php

Time:01-10

I've been watching a video about basic connection to MySQL in PHP. And tried to hide the content of error from "Fatal error: Uncaught mysqli_sql_exception: php_network_getaddresses...." to for example "Error 2002". I tried some of ways but it still shows the whole text. My code: I also tried to use try/catch block but it still shows the whole text. I use vs code and PHP 8.1

   <?php 
     require_once "connect.php";

      $connection = @new mysqli($host,$db_user,$db_passw,$db_name);

      if($connection->connect_errno != 0){
       echo "Error ".$connection->connect_errno;             // <- this place
       //echo mysqli_report($connection->connect_errno);
       //die($connection->connect_errno);
       }else{
         $login = $_POST['username'];
         $passw = $_POST['password'];
  
        $connection -> close();
      }
   ?>

///////////////////////////////////////////////////////////// ............

      try {
         $connection = @new mysqli($host,$db_user,$db_passw,$db_name);
       } catch (Exception $e) {
               echo 'Caught exception: ',  $e->getMessage(), "\n";
      }

      ...........

CodePudding user response:

It shows the full error message because you literally ask for it:

echo 'Caught exception: ', $e->getMessage(), "\n";

If you want to display the numeric error code, just do so:

echo 'Error ', $e->getCode(), "\n";

Something to note is that mysqli_report() does not seemingly prevent all warnings. It feels like an implementation oversight, but I don't have more information about it. For that, the error suppression operator @ you're already using should suffice.

Also, don't forget to disable the display_errors directive in your production server.

Finally, Mysqli only throw exceptions on errors by default since PHP/8.1. In earlier versions you need to set it explicitly:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  •  Tags:  
  • Related