Question

Okay, so I have some code here:

<?php

$rt = 'abc'; $imdb = 'defg';
if ($con = mysqli_connect($a,$b,$c,$d)) {
    if (mysqli_query($con,"DELETE FROM blah WHERE a = '{$imdb}'")){
        echo 'Deleted!';
        if (mysqli_query($con, "INSERT INTO foo (c,d) VALUES ('{$rt}','{$imdb}')")){
        echo 'Inserted after deletion!'
            if (mysqli_query(...)) {
                 if (mysqli_query(....)) {

                 }
            }
        }
    }
}

Some of my programs have many queries in a row, each of which is dependent on the result of a previous query. However, creating error handling for every single query and making sure that the logic of the code stays the same (not to mention staying readable) throughout can be a somewhat tedious and error prone process.

I would like to know a bit more about what is going on behind the scenes when a query is sent, because it would help me a lot with some of my questions. Namely, is it really necessary to write if (mysqli_query()) all the time for correct error handling, or is simply checking if the so-called 'master' connection exists enough?

That is, after I check mysqli_connect(), do I have to check every subsequent query within that connection to see if it went through (connection-wise, not logic-wise), or is it simply enough to check mysqli_connect() once, at the beginning of the program? It would sure make things a lot easier.

Also, while I'm looking at mysqli_multi_query() for more practical query management, I would prefer not to use it until I can fully understand the simpler query functions.

Thanks for your help!

Was it helpful?

Solution

Only few things for you to get it right

  1. You have to distinguish an error from a query result. If your query depends on the result of the another one - it's all right to check the result. But if you want to check for the error - there are better ways.
  2. In a properly written application a query error is a highly exceptional event, and there shouldn't be code written to handle it in place. It have to be done somewhere else.
  3. mysqli can throw an exception in case of error, which is actually a Holy Grail you are looking for.

So, if you want to stop your code if one of queries failed, just set mysqli in exception mode and then pile your queries one after another.

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect($a,$b,$c,$d);

$rt = 'abc'; $imdb = 'defg';
mysqli_query($con,"DELETE FROM ...");
mysqli_query($con, "INSERT INTO ...");
mysqli_query(...);
mysqli_query(...);
...

And two additional notes

  • if you want to undo a previous query if following one failed, then use transactions
  • you should NEVER write a query like you do, interpolating a variable directly into it. You ought to use prepared statements, substituting every variable with placeholder in the query.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top