PHP does not throw an exception if mysqli is not enabled

I have

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once "configuration.php";
header('Content-Type: application/json');
try
{   
    $mysqli = new mysqli(MYSQL_SERVER, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);
    $mysqli->set_charset("utf8");
} catch (Exception $e) {
    echo json_encode(
        array(
            'msg' => $e->getMessage()
        )
    );
}

And if mysqlinot enabled, it will not catch the error:

Fatal error : Unused error: class 'mysqli' not found in C: \ test \ db_connect.php: 8
    Stack trace:
    # 0 C: \ test \ getContacts.php (2): require_once ()
    # 1 {main} thrown into C: \ test \ db_connect.php on line 8

What can I do to make it detect an error?

I tried this one but it did not work:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once "configuration.php";
header('Content-Type: application/json');
try
{
    if(!extension_loaded('mysqli'))
    {
        throw new Exception('mysqli is not enabled');
    }

    $mysqli = new mysqli(MYSQL_SERVER, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);
    $mysqli->set_charset("utf8");
} catch (Exception $e) {
    echo json_encode(
        array(
            'msg' => $e->getMessage()
        )
    );
}

This does not stop, the script continues to run.

{ "msg": "mysqli " }
: Undefined variable: mysqli in C:\test\getContacts.php 99
    

     : : --() null C:\test\getContacts.php: 99      :     # 0 {main}        C:\test\getContacts.php 99

+4
2

, , , , . ,

if(!function_exists('mysqli_connect')) {
    throw new Exception('mysqli is not enabled');
}
+7

php-7: php 7 , Exception, -:

...
} catch (Error $e) {
         ^^^^^ Not Exception
    echo json_encode(
        array(
            'msg' => $e->getMessage()
        )
    );
    // stop execution
    exit;
}

php 7 . .

+2

Source: https://habr.com/ru/post/1650592/


All Articles