Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP / MySQL: Catch syntax errors in queries

I want to prepare an API for my database (mySQL) in php.
Now I did some tests.

function getUsers($req)
{
    $data = array();

    $db = connect();
    $sql = "SELECT * FROM mydb.users;";
    $result = $db->query($sql, 1);
    if ($result) {
        $data['data'] = dataToJson($result);
        $data['statusCode'] = 200;
        $data['statusMessage'] = 'OK';
    } else {
        $data['data'] = null;
        $data['statusCode'] = 500;
        $data['statusMessage'] = $db->error;
    }
    disconnect($db);
    sendData($data);
}

So this works fine but there is one problem: When there is a syntax error in my query ($sql), the code is not executed. I would expect that the else case is executed but actually no code at all is executed, when there is a syntax error in the query.
Instead of executing the else-case, the browser throws the error:

VM994:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When inspecting VM994:1

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” at line 1

Is it at all possible to catch faulty queries with PHP?

>Solution :

When an exception occurs, the system goes into an error state and the code that follows is no more executed. You should handle the exception and do whatever you need for your purposes. For example:

function getUsers($req)
{
    try {
        $data = array();
        $db = connect();
        $sql = "SELECT * FROM mydb.users;";
        $result = $db->query($sql, 1);
        if ($result) {
            $data['data'] = dataToJson($result);
            $data['statusCode'] = 200;
            $data['statusMessage'] = 'OK';
        } else {
            throw new Exception("Query failed");
        }
    } catch (Exception $ex) {
        // exception occurred, do here whatever you need, for example
        $data['data'] = null;
        $data['statusCode'] = 500;
        $data['statusMessage'] = $ex->getMessage();
    } finally {
        // do here what you want to be always executed even if there is an exception, for example
        disconnect($db);
        sendData($data);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading