我想在PHP类中包含MySQL配置文件。
<?php
class User {
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "gic";
private $userTbl = 'users';
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
function checkUser($userData = array()){
if(!empty($userData)){
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path ."/";
$prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
$prevResult = $this->db->query($prevQuery);
<!-- rest of my code -->
}
}
}
当我运行此文件时,它工作正常,但我想将MySQL数据库连接与另一个文件(config.php)分开,所以我编辑了我的代码:
<?php
class User {
include 'config.php';
$connection = new createCon();
$conn = $connection->connect();
function checkUser($userData = array()){
if(!empty($userData)){
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path ."/";
$prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
$prevResult = $conn->query($prevQuery);
}
}
}
和config.php
<?php
class createCon {
var $host = 'localhost';
var $user = 'root';
var $pass = '';
var $db = 'gic';
var $myconn;
function connect() {
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
if (!$con) {
die('Could not connect to database!');
} else {
$this->myconn = $con;
echo 'Connection established!';}
return $this->myconn;
}
function close() {
mysqli_close($myconn);
echo 'Connection closed!';
}
}
?>
当我运行上面的代码时,它显示错误:
解析错误:语法错误,意外&#39;包含&#39; (T_INCLUDE),期望第4行的C:\ xampp \ htdocs \ gic001 \ User.php中的函数(T_FUNCTION)或const(T_CONST)
有什么想法吗?
答案 0 :(得分:0)
尝试在课堂外移动包含。
<?php
require('config.php');
class User {
否则将其放在函数内:
class User {
protected $conn;
public function __construct(){
$this->loadConfig();
}
protected function loadConfig(){
require('config.php');
$connection = new createCon();
$this->conn = $connection->connect();
}
您还想要了解的内容:
答案 1 :(得分:0)
坦率地说,你的整个方法都是错误的。
A user is not a database!用户类中永远不应该有这样的属性作为$ dbHost。也不应该费心去连接数据库。用户类应该只使用其他地方定义的连接。
您应该创建一个数据库实例一次。然后将它作为参数传递给用户的构造函数方法
class User {
protected $conn;
public function __construct($conn) {
$this->conn = $conn;
}
function checkUser($userData = array()){
$prevResult = $this->conn->query($prevQuery);
}
}
所以只需包含您的凭据一次,即创建连接的位置。
答案 2 :(得分:-1)
继承,这应该不是一个大问题。保持您的配置文件不变并尝试此操作。
include_once 'config.php';
class User extends createCon {
private $conn;
function __construct(){
$this->conn = $this->connect();
}
}