user56489870 user56489870 - 2 months ago 6
MySQL Question

is checking the failure of every db query considered a good php coding habit?

I'm coding PHP for just about 4 months .and I never saw big php scripts and I don't know how do they look like. and I was wondering "Do I really need to do this for every single query?"

$result= $mysqli->query("select * from clients;");
if(!result){
//error. log it and echo a proper message
}else{
//show the clients
}


Do I need to do this for every single query I do in my final production code? because my php scripts now are full of
if(!$result)
if(!$result)
if(!$result)
if(!$result)
if(!$result)
. does not that consume more time for parsing which means more response delay

Note: off-curse I test the data base connection at the very top of my php script before I go on

Answer

Yes, you should check for errors. First of all, its helpful for debugging and since you should run as less queries as possible per request it wont make any noticeable difference in loading speed. So there is no reason, why you should not do it.

So why don't you create your own database class which does that automatically? You would only have to write it once.

class Database
{
    /* ... */
    private $connection = null;

    public function __construct($host, $user, $password, $database)
    {
        // connect
    }


    public function query($query)
    {
        $result = $this->mysqli->query($query);
        if(!result)
        {
            // error
        }
        else
        {
            return $result;
        }
    }

    public function __destruct()
    {
        // deconnect
    }
}

Call it like that:

$db = new Database($host, $user, $password, $database);
$result = $db->query("select * from clients;");