Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP does not throw exception if mysqli is not enabled

Tags:

php

php-7

mysqli

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 mysqli is not enabled then it does not catch the error:

Fatal error: Uncaught 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 in C:\test\db_connect.php on line 8

What can I do so that it catches the error?

I have tried this one but it didn't 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 one does not halt, continues to execute the script.

{"msg":"mysqli is not enabled"}
Notice: Undefined variable: mysqli in C:\test\getContacts.php on line 99

Fatal error: Uncaught Error: Call to a member function query() on null in C:\test\getContacts.php:99 Stack trace: #0 {main} thrown in C:\test\getContacts.php on line 99

like image 990
ilhan Avatar asked Jan 06 '23 14:01

ilhan


1 Answers

It's odd that it wouldn't be installed but if you're rolling your own I guess it could be omitted. I would check to see if the procedural functions exist

if(!function_exists('mysqli_connect')) {
    throw new Exception('mysqli is not enabled');
}
like image 187
Machavity Avatar answered Jan 15 '23 07:01

Machavity