I want to include MySQL config file inside PHP class.
<?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 -->
}
}
}
When I run this file, it's working fine, but I want to separate the MySQL database connection to another file (config.php), so I edited my code:
<?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);
}
}
}
and 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!';
}
}
?>
When I run the code above, it's showing an error:
Parse error: syntax error, unexpected 'include' (T_INCLUDE), expecting function (T_FUNCTION) or const (T_CONST) in C:\xampp\htdocs\gic001\User.php on line 4
Any idea?
With inheritance, it should not be a big problem. Keep your config file as it is and try this.
include_once 'config.php';
class User extends createCon {
private $conn;
function __construct(){
$this->conn = $this->connect();
}
}