PHP与mysqli的连接错误
在程序化PHP之后,我从上周开始研究OOP的基本原理,并尝试连接数据库。 但它显示了我意想不到的错误:
意外'$ conn'(T_VARIABLE),期望函数(T_FUNCTION)
PHP代码:
class Database
{
public $conn;
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "inventory";
// Create connection
$conn = new mysqli($host, $user, $pass, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
}
尝试这个 :
<?php
class Database {
public $conn;
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "inventory";
public function __construct()
{
// Create connection
$this->conn = new mysqli($this->host, $this->user, $this->pass, $this->db);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
echo "Connected successfully";
}
public function getCon() {
return $this->conn;
}
}
?>
你需要一个构造函数。 只需使用你的课程:
$oDatabase = new Database();
您需要获得$ conn的访问权限;
您必须将连接代码存储到函数中。 不要忘记删除public $conn;
从一开始。
public function createConnection ()
{
// Create connection
$conn = new mysqli($this->host, $this->user, $this->pass, $this->db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
return $conn;
}
然后你可以创建一个类的对象。
$db = new Database(); // Your main object
$conn = $db->createConnection(); // The connection object
请注意,我一直使用$ this->变量来访问你的类中的私有变量。
现在你可以使用连接对象。 例如$conn->query("SELECT * FROM MyTable");
你的班级没有任何功能。 例如,你需要一个connect()来连接数据库。
class Database {
// public $conn;
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "inventory";
// Create connection
function connect() {
$conn = new mysqli($host, $user, $pass,$db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
}
}
链接地址: http://www.djcxy.com/p/58073.html