<?
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();
}
}
mysqli::query
函数的返回类型是混合的,因此它取决于您发送的$sql
查询。
如果查询类似于"CREATE TABLE myTable like anotherTable;"
,则查询的返回是TRUE
或FALSE
。另一方面,如果它真的是一个SELECT
查询,如果操作不成功,您应该期待FALSE
,否则您将有一个$result
对象。
所以在执行操作之前最好检查CCD_ 9的类型。我建议在你的代码中添加一些检查,如下所示:
public function query($sql){
$result = $this->connection->query($sql);
$records = array();
if($result === FALSE)
return FALSE;
if ($result->num_rows == 0) {
return null;
....
}