我有2个文件
MySQLi.php
$MySQLi = new mysqli($DB_ServerName, $DB_UserName, $DB_Password, $DB_Name);
if($MySQLi->connect_error)
{
...
}
else
{
...
}
Articles.php
class Articles
{
public function AddArticle()
{
if ($MySQLi->query("INSERT INTO articles (Title, ArticleContent, Author) VALUES ('Title', 'Content', 'Author')") === TRUE)
{
...
}
else
{
...
}
}
}
如何在Articles类中使用$ MySQLi?
答案 0 :(得分:2)
如评论中所述,您应该将连接对象文件包含在另一个文件中。
另一种选择是: -
1) 使连接类静态以处理mysqli对象。
class DBConnection {
public static $con;
}
DBConnection::$con = new mysqli(YOUR_HOST, YOUR_USER, YOUR_PASS, YOUR_DB);
在其他文件中,静态调用如下: -
DBConnection::$con->query(...); // execute your query
2)您也可以通过创建类和对象来实现。
class Connection{
public $conn;
function __construct($host='YOUR_HOST',$user='YOUR_USER',$pass='YOUR_PASS',$db='YOUR_DB'){
$this->conn = new mysqli($host, $user, $pass, $db);
}
}
然后创建Connection类的对象
$object = new Connection(); // pass connection params if you want to overwrite default connection params
$object->conn->query(..); // execute your query