当前位置:Gxlcms > PHP教程 > 小白第一次发帖求教,php连接mysql时用面向对象的风格报错,代码如下

小白第一次发帖求教,php连接mysql时用面向对象的风格报错,代码如下

时间:2021-07-01 10:21:17 帮助过:17人阅读

小弟学生党一枚,最近迷恋上了php编程,有遇到问题刨根问底的坏习惯,代码描述如下,大神们勿喷。。。


class SqlHelper{
// public $host='loaclhost';
// public $user='root';
// public $password='root';
// public $database='empmanage';
// public $mysqli;

public function __construct(){
$this->mysqli=new mysqli('localhost','root','root','empmanage');
$this->mysqli=new mysqli($this->host,$this->user,$this->password,$this->databse); //这个连接不上。不论是把private改成public,还是加static用self访问。

if($this->mysqli->connect_error){
die('连接失d败'.$this->mysqli->connect_error);
}
$this->mysqli->query('set names utf8');
}

public function execute_dql($sql){
$result=$this->mysqli->query($sql) or die('操作1失败'.$this->mysqli->error);// 查询语句,会返回数据
return ($result);
}


问题出在了红色代码上,当用 $this->mysqli=new mysqli($this->host,$this->user,$this->password,$this->databse)访问的时候会报错,说:连接失d败,没有这样的主机;这段代码无论怎么改都不行,我试过用self::访问静态变量(在成员属性加了static),试过把private改成public,最终都会失败然后报另一个错误:操作1失败,没有选择数据库;最后我发现只有把里面的代码敲进去才行,就是红色上面那行,小弟这里就不知道哪里出错了,技术不过关,有劳大神们了。


回复讨论(解决方案)

注意单词的拼写
public $host=' localhost';


$this->mysqli=new mysqli($this->host,$this->user,$this->password,$this-> database);

拼写错误。。。database

下次楼主遇到这个问题的话可以把整个语段输出来看看哪些没赋值上不就知道了么


嘿嘿真的是单词拼写错了,我真是太粗心大意了,谢谢大家

人气教程排行