I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.
This is my class
class User {
$dbconn = include("config.php");
private $dbHost = $dbconn->host;
private $dbUsername = $dbconn->username;
private $dbPassword = $dbconn->pass;
private $dbName = $dbconn->database;
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;
}
}
}
}
This is my config.php file
return (object) array(
'host' => 'localhost',
'username' => 'my_user',
'pass' => 'my_pass',
'database' => 'my_db'
);
How do i do it?
PHP Parse error: syntax error, unexpected '$dbconn' (T_VARIABLE)
You can't have executable code in a variable definition, only static values. So this sort of thing is not supported:
class foo {
public $var = result_of_some_function();
}
If you want to initialize a value, use the constructor. You're probably better off reading it as a config file:
class User {
public function __construct() {
$config = json_decode(file_get_contents('config.json'));
$conn = new mysqli($config->host, ...);
}
}
Or better, using dependency injection:
class User {
protected $db = null;
public function __construct($db) {
$this->db = $db;
}
}
Then in your code that creates a user object:
$db = new Db($config);
$user = new User($db);
The other way is to define constants in config file and use them in class.
in config.php file
define('HOST', 'localhost');
define('USERNAME', 'my_user');
define('PASS', 'my_pass');
define('DATABASE', 'my_db');
In class file
include("config.php")
class User {
private $dbHost = HOST;
private $dbUsername = USERNAME;
private $dbPassword = PASS;
private $dbName = DATABASE;
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;
}
}
}
}
Include this:
$dbconn = include("config.php");
in your construct function.
Maybe you should change in your code to
function __construct()
{
//included db file
include 'config.php';
if (!isset($this->db))
{
//code here
}
Try this way of using it.
<?php
class User
{
private $dbconn = null;
private $dbHost;
private $dbUsername;
private $dbPassword;
private $dbName;
private $userTbl = 'users';
function __construct()
{
include 'config.php'; //included file in constructor
if (!isset($this->db))
{
$this->dbHost= $this->dbconn->host;
$this->dbUsername= $this->dbconn->username;
$this->dbPassword= $this->dbconn->pass;
$this->dbName= $this->dbconn->database;
// 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;
}
}
}
}
Config.php
<?php
$this->dbconn= (object) array(
'host' => 'localhost',
'username' => 'my_user',
'pass' => 'my_pass',
'database' => 'my_db'
);
Related
Hi i am working on a basic databse connection class for mysql using PDO, however when i var dump the return result it tells me i has 2 objects: object(PDO)[2]. Should it not be only one ?
Here is my code so far:
class DBConnection
{
// Settings (DSN)
protected $driver, $host, $name, $charset;
// Credentials
protected $user, $pass;
// PDO Connection
protected $connection;
public function __construct() {
require_once( 'database.config.php' );
// Settings (DSN)
$this->driver = DB_DRIVER;
$this->host = DB_HOST;
$this->name = DB_NAME;
$this->charset = DB_CHARSET;
// Credentials
$this->user = DB_USER;
$this->pass = DB_PASS;
// Initialise Connection
var_dump($this->getConnection());
}
private function getConnection() {
// Check if connection is already established
if ( $this->connection == NULL ) {
$dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
try {
$this->connection = new PDO($dsn,$this->user, $this->pass);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $error ) {
echo 'Connection failed: ' . $error->getMessage();
}
}
return $this->connection;
}
}
$new = new DBConnection();
Config file:
define('DB_DRIVER', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASS', '');
private function getConnection() {
// Check if connection is already established
if ( $this->connection == NULL ) {
$dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
try {
$this->connection = new PDO($dsn,$this->user, $this->pass);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This line is to remove associate array, then you will get only one object in result set
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch ( PDOException $error ) {
echo 'Connection failed: ' . $error->getMessage();
}
}
return $this->connection;
}
I am using a config.php file for a simular something, im trying to put my mysql credentials in there to then use them in a different file, but it does not pass the values,
is there any1 that could help me find a solution.
code config.php:
/* Database credentials*/
$dbHost = 'localhost';
$dbName = 'xx';
$dbUsername = 'xx';
$dbWachtwoord = 'xx';
code dbconnect.php:
<?php include 'config.php';
class Database
{
private $host;
private $db_name;
private $username;
private $password;
public $conn;
public function dbConnection()
{
$this->host = $dbHost;
$this->db_name = $dbName;
$this->username = $dbUsername;
$this->password = $dbWachtwoord;
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Class.user dbconnection:
<?php
require_once('config.php');
require_once('dbconnect.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
Thanks in advance =)
Rather than thinking about it as passing variables, think about it as passing configuration. It is necessary for your Database class to be aware of those configuration options in order for it to be used. In other words: once you create an instance of class Database it should be configured and ready to use, just like any service would.
I strongly suggest you follow the rule of injecting the configuration as a dependency.
Include 'config.php inside your class
public function dbConnection()
{
include 'config.php';
$this->host = $dbHost;
$this->db_name = $dbName;
$this->username = $dbUsername;
$this->password = $dbWachtwoord;
$this->conn = null;
try
{
You can try below code :
config.php
<?php
return [
'dbHost' => 'localhost',
'dbName' => 'xx',
'dbUsername' => 'xx',
'dbWachtwoord' => 'xx',
];
user class
class USER
{
private $conn;
private $config;
public function __construct()
{
$this->config = include "config.php";
$database = new Database(this->config['dbHost'], $this->config['dbUsername'], $this->config['dbWachtwoord'], $this->config['dbName']);
//...
}
//...
}
dbconnect.php
public function dbConnection($dbHost, $dbName, $dbWachtwoord, $dbName)
{
//....
}
I've got two files dbconnect.php and config.php
dbconnect.php
<?php
class connect{
public function __construct(){
$config = require_once __DIR__ . 'config.php';
}
private $dbhost = $config['host'];
private $dbuser = $config['username'];
private $dbpass = $config['pass'];
private $dbname = $config['dbname'];
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
?>
config.php
<?php
/**
* Contains all configurations
*
*/
return [
'dbname' => 'user',
'pass' => '#user.intern1',
'username' => 'user1',
'host' => 'localhost',
];
?>
in my dbconnect.php file;
how do I include variables from my config.php into the class connect
If I do it the following way above;
it yells at me and gives me Fatal error:
"Parse error: syntax error, unexpected '$config' (T_VARIABLE) in C:\xampp\htdocs\hngfun\profile\adeojoemmanuel\php-handler\dbconfig.php on line 8"
I'm taking a guess here. But I can clearly see that you are setting $config as a local variable in the constructor. That means it is not available once you leave the constructor.
<?php
class connect{
public function __construct(){
$config = require_once __DIR__ . 'config.php';
$this->dbhost = $config['host'];
$this->dbuser = $config['username'];
$this->dbpass = $config['pass'];
$this->dbname = $config['dbname'];
}
private $dbhost ;
private $dbuser ;
private $dbpass ;
private $dbname ;
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
Declared properties like private $dbhost cannot be assigned values that are dependent on runtime data, such as $config['host'];
Quoting from the PHP Docs:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
The solution, assign the values in your constructor:
class connect{
public function __construct(){
$config = require_once __DIR__ . 'config.php';
private $this->dbhost = $config['host'];
private $this->dbuser = $config['username'];
private $this->dbpass = $config['pass'];
private $this->dbname = $config['dbname'];
}
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
You need to set inside constructor:
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
public function __construct(){
$config = require_once __DIR__ . 'config.php';
$this->dbhost = $config['host'];
$this->dbuser = $config['username'];
$this->dbpass = $config['pass'];
$this->dbname = $config['dbname'];
}
The first problem is that you can't just return anything from your config.php file. You can only return a result inside a function. One way to implement this is to declare the array as a global variable and then use it inside all other php files that would need that configuration array.
<?php
/**
* Contains all configurations
*
*/
$dbconfig = array(
'dbname' => 'user',
'pass' => '#user.intern1',
'username' => 'user1',
'host' => 'localhost',
);
?>
<?php
require_once __DIR__ . 'config.php';
class connect{
public function __construct(){
}
private $dbhost = $dbconfig['host'];
private $dbuser = $dbconfig['username'];
private $dbpass = $dbconfig['pass'];
private $dbname = $dbconfig['dbname'];
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
?>
In JSP, if I want to connect to the database, I would create a Java class called DBManager with the following code:
public class DBManager {
private final static String DB_URL = "jdbc:mysql://localhost:3306/mydb";
private final static String DB_USERNAME = "root";
private final static String DB_PASSWORD = "root";
public static Connection conn = null;
private static Statement stmt = null;
/**
* Tests connection with the database by getting connection using the
* database url and username and password. And creates a dumb statement and
* closes it to make sure everything is working fine.
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
stmt = conn.createStatement();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now, I can easily do something like:
PreparedStatement pstmt = DBManager.conn.prepareStatement("SELECT * FROM USER");
I'm learning PHP on my own and "most" of the online tutorials actually don't teach how to do stuff the right way.
They all do it in the traditional way in each page they need a connection:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Which is wrong because say you want to change your password? Then, you have to change it in each and every page that you used that password.
My question: how can I do something equivalent/similar to that Java class in PHP?
EDIT:
<?php
class DBManager {
public static $conn = null;
private static $hostname = "localhost";
private static $username = "root";
private static $password = "root";
private static $dbname = "tutorme";
protected function __construct() {
try {
DBManager::$conn = new PDO("mysql:host=localhost;dbname=tutorme", DBManager::$username, DBManager::$password);
DBManager::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
public static function getInstance() {
if (null === DBManager::$conn) {
DBManager::$conn = new DBManager();
}
return DBManager::$conn;
}
}
?>
I searched a little and came up with the above code. However, now when I call
$stmt = DBManager::getInstance()->prepare("INSERT INTO SUBJECT (SubjectTitle, SubjectName) VALUES (:subject,:subj)");
I get an error that there's no function in DBManager called prepare()
which means that my DBManager::getInstance is returning a DBManager object instead of PDO conn object
You have one obvious mistake:
DBManager::$conn = new DBManager();
You don't want that!
Just call new DBManager() and the $conn var will be initiliazed!
And also here are some minor changes,
<?php
class DBManager {
public static $conn = null;
private static $hostname = "localhost";
private static $username = "root";
private static $password = "root";
private static $dbname = "tutorme";
private function __construct() {
try { // why not using $hostname and $dbname?!
DBManager::$conn = new PDO("mysql:host=" . DBManager::$hostname . ";dbname=" .DBManager::$dbname, DBManager::$username, DBManager::$password);
DBManager::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
// getConnection() is a better naming of the function
public static function getConnection() {
if (is_null(DBManager::$conn)) {
new DBManager();
}
// now $conn is initialized
return DBManager::$conn;
}
}
?>
make a class just like what's in java and let's call it database.php
in the file u want to do something
include 'database.php';
.... your code .....
tip: look for "autoload"
is that what you want?
you can start off with this
class Database{
function __construct(){
$this->host = HOST;
$this->user = DB_USER;
$this->pass = DB_PASS;
$this->db = DATABASE;
$this->con = $this->connect();
}
function connect(){
$q = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
if($q) return $q; die("Couldn't Connect to Database");
}
}
other file like so for example
include 'Database.php';
$db = new Database();
mysqli_query($db->con, "QUERY_HERE");
Is it possible to keep all my database related configuration (hostnames, usernames, passwords, and databases) as well as the function to connect to and select the correct database in a separate class?
I tried something like this:
class Database
{
var $config = array(
'username' => 'someuser',
'password' => 'somepassword',
'hostname' => 'some_remote_host',
'database' => 'a_database'
);
function __construct() {
$this->connect();
}
function connect() {
$db = $this->config;
$conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
if(!$conn) {
die("Cannot connect to database server");
}
if(!mysql_select_db($db['database'])) {
die("Cannot select database");
}
}
}
And then in another class I would use in the classes __construct function:
require_once('database.php');
var $db_conn = new Database();
But this doesnt save the connection, it ends up defaulting to the servers local db connection. Or do I have to do the database commands everytime before I execute some database commands?
I modified your class to work as you seem to be expecting it to:
<?php
class Database
{
var $conn = null;
var $config = array(
'username' => 'someuser',
'password' => 'somepassword',
'hostname' => 'some_remote_host',
'database' => 'a_database'
);
function __construct() {
$this->connect();
}
function connect() {
if (is_null($this->conn)) {
$db = $this->config;
$this->conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
if(!$this->conn) {
die("Cannot connect to database server");
}
if(!mysql_select_db($db['database'])) {
die("Cannot select database");
}
}
return $this->conn;
}
}
Usage:
$db = new Database();
$conn = $db->connect();
Note that you can call connect() as many times as you like and it will use the current connection, or create one if it doesn't exist. This is a good thing.
Also, note that each time you instantiate a Database object (using new) you will be creating a new connection to the database. I suggest you look into implementing your Database class as a Singleton or storing it in a Registry for global access.
You can also do it the dirty way and shove it in $GLOBALS.
Edit
I took the liberty of modifying your class to implement the Singleton pattern, and follow the PHP5 OOP conventions.
<?php
class Database
{
protected static $_instance = null;
protected $_conn = null;
protected $_config = array(
'username' => 'someuser',
'password' => 'somepassword',
'hostname' => 'some_remote_host',
'database' => 'a_database'
);
protected function __construct() {
}
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function getConnection() {
if (is_null($this->_conn)) {
$db = $this->_config;
$this->_conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
if(!$this->_conn) {
die("Cannot connect to database server");
}
if(!mysql_select_db($db['database'])) {
die("Cannot select database");
}
}
return $this->_conn;
}
public function query($query) {
$conn = $this->getConnection();
return mysql_query($query, $conn);
}
}
Usage:
$res = Database::getInstance()->query("SELECT * FROM foo;");
or
$db = Database::getInstance();
$db->query("UPDATE foo");
$db->query("DELETE FROM foo");
You can certainly keep your connection info in a separate file.
Just save your connection object - $conn in your connect() function - in a class variable. You'll then be able to reuse it across calls.
In your method connect() $conn is only a local variable that only exists in the scope of that method. As soon as the method returns there will be no (other) reference to the connection resource and it will be collected/disposed.
You'll need at least
$this->conn = mysql_connect(...)
Here comes the singleton with PDO example. Thanks to #hodobave
<?php
/**
* DB Connection class
* Singleton pattern
* An single instance of DB connection is created
**/
class Db{
protected static $_instance = null;
protected $_conn;
protected $_config = [
'username' => 'root',
'password' => '',
'hostname' => 'localhost',
'database' => 'news',
];
protected function __construct(){
}
public function getInstance(){
if(null === self::$_instance){
self::$_instance = new self();
}
return self::$_instance;
}
public function getConnection(){
if(is_null($this->_conn)){
//connect here
$db = $this->_config;
$dsn = "mysql:host={$db['hostname']};dbname={$db['database']}";
$this->_conn = new PDO($dsn, $db['username'], $db['password']);
}
return $this->_conn;
}
public function query($sql){
$args = func_get_args();
array_shift($args);
$statement = $this->getConnection()->prepare($sql);
$statement->execute($args);
return $statement->fetchAll(PDO::FETCH_OBJ);
}
}
$res = Db::getInstance();
$users = $res->query("SELECT * FROM `user` WHERE id=?",1);
print_r($users);
?>