<?
class Db {
private $connection;
public function __construct($option = null){
if ($option != null){
$host = $option['host'];
$user = $option['user'];
$pass = $option['pass'];
$name = $option['name'];
}else {
global $config;
$host = $config['db']['host'];
$user = $config['db']['user'];
$pass = $config['db']['pass'];
$name = $config['db']['name'];
}
$this->connection = new mysqli($host, $user, $pass, $name);
if ($this->connection()->connect_error){
echo("Connection failed: " .$this->connection->connect_error);
exit;
}
$this->connection->query("SET NAMES ''utf8");
}
public function first($sql) {
$records = $this->query($sql);
if ($records == null){
return null;
}
return $records[0];
}
public function query($sql){
$result = $this->connection->query($sql);
$records = array();
if ($result->num_rows == 0) {
return null;
}
while ($row = $result->fetch_assoc()) {
$records[] = $row;
}
return $records;
}
public function connection(){
return $this->connection;
}
public function close(){
$this->connection()->close();
}
}
The return type of the mysqli::query
function is mixed so it depends on the $sql
query you are sending.
If the query is something like "CREATE TABLE myTable like anotherTable;"
the return of the query is either TRUE
or FALSE
. On the other hand if it is really a SELECT
query, if the operation is not successful you should expect FALSE
otherwise you have a $result
object.
so it is better check the type of $result
before performing operations. I suggest add some checking in your codes like follows:
public function query($sql){
$result = $this->connection->query($sql);
$records = array();
if($result === FALSE)
return FALSE;
if ($result->num_rows == 0) {
return null;
....
}