You do not need to use fetch_assoc()
most of the time. If you are writing some kind of abstraction class around mysqli then you should never need to use any of mysqli functions directly.
mysqli:query()
returns an object of type mysqli_result
which is iterable. This means you can use foreach
loop to iterate over it.
I need to point out that you are still following some bad programming practices. You should never use or die($this->con->error.__LINE__)
. This is a terrible coding practice and completely unnecessary. Instead, you should enable proper error reporting. See How to get the error message in MySQLi?
Your select()
method should return only an array. This would make your code much easier and less error-prone. So rewrite your select()
function to this:
public function select($sql){
return $this->con->query($sql)->fetch_all(MYSQLI_ASSOC);
}
As you can see the whole functionality is a single line of code, which means your select()
method is not very useful. You can replace it with something more generic instead. This way you avoid a lot of code repetition.
public function executeQuery(string $sql, array $params = []): ?array {
// Prepare/bind/execute
$stmt = $this->con->prepare($sql);
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
$stmt->execute();
// If it was a select query which gives result then return results in an array
if ($result = $stmt->get_result()) {
return $result->fetch_all(MYSQLI_BOTH);
}
// If it is INSERT/UPDATE then return null instead of array
return null;
}
Of course this method should not be part of your model. It should be part of a dedicated class for database communication. You can then create a single instance of it in your application and pass it to your model.