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
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;");
You can also do this:
$select = $mysqli->query('SELECT * FROM users');
$delete = $mysqli->query('DELETE FROM customers');
$update = $mysqli->query('UPDATE table SET id={$id}');
if(!$select || !$delete || !$update) {
// error messages
} else {
// executions for each variable
}
But if you want different error messages for error handling for each of your variable, what you're doing is a good practice.
Yes. Do it. Every database interaction.
If you're concerned with the overhead of checking the return from every database interaction... I'd tend to be worried about the number of database interactions you are running. Compared to the expense of running an unnecessary query, or an inefficient query, or even a loop of very efficient queries which could be performed with a single query.... the check for FALSE does not move the needle.
If you want to worry about the length of the code path, take a look at what's going on "under the covers" in mysqli or PDO. Or take a look at one of the ORM frameworks. That check for FALSE doesn't even tickle the needle on the gauge.
Definitely look at streamlining the error logging, so your code isn't as cluttered handling the error. And by streamlining, I do not mean just
... or die(mysqli_error($con));