<?
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();
}
}
我正在尝试设置类,但继续在第41行获取错误“num_rows行”,错误是“试图获取第41行中非对象的属性”
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- dstxpei5823 2016-03-31 11:39关注
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 eitherTRUE
orFALSE
. On the other hand if it is really aSELECT
query, if the operation is not successful you should expectFALSE
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; .... }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 乘性高斯噪声在深度学习网络中的应用
- ¥15 运筹学排序问题中的在线排序
- ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
- ¥30 求一段fortran代码用IVF编译运行的结果
- ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
- ¥15 C++ 头文件/宏冲突问题解决
- ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
- ¥50 安卓adb backup备份子用户应用数据失败
- ¥20 有人能用聚类分析帮我分析一下文本内容嘛
- ¥30 python代码,帮调试,帮帮忙吧