您好我在使用OO PHP连接到我的数据库时遇到了一些问题。我的脚本如下。我已经有一段时间了。这只是一个测试脚本,因为我对OOP相当新。请不要苛刻
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$mysqli = new mysqli($host, $username, $password, $db);
if (!$mysqli){
echo "error in connecting to database";
}
else{
echo "success in connecting to database";
}
}
public function query(){
$result = $mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
...用法
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
答案 0 :(得分:1)
您的主要问题是您没有将值存储到类“$mysqli
属性中。您需要在构造函数和查询方法中使用$this->mysqli
,而不是$mysqli
。
其次,这个类添加了{strong>没有 mysqli
类还没有。你也可以简单地使用
$DB = new mysqli('localhost', 'root', 'xxxx', 'yyyy');
if ($DB->connect_error) {
throw new Exception($DB->connect_error, $DB->connect_errno);
}
答案 1 :(得分:0)
问题是,您正在访问没有$this
的类属性。 $mysqli
应该在构造函数中的$this->mysqli
中。
您使用 mysqli 属性作为mysqli
类的对象。
然后您可以在查询函数中使用$this->mysqli->query("SELECT * FROM inventory")
的 mysqli属性对象(在数据库类中)的查询函数。
更新代码:
<?php
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->mysqli = new mysqli($host, $username, $password, $db);
/* check connection */
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
} else {
echo "success in connecting to database";
}
}
public function query(){
$result = $this->mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
答案 2 :(得分:-3)
试试这个:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_error()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}