PHP - Calling database class from another class - php

I've recently encountered an error in my code:
PHP Parse error: syntax error, unexpected '$connection' (T_VARIABLE), expecting function (T_FUNCTION) in
From what I've googled the issue is not setting public/private/protected before, or not creating the database connection in the construct function.
The database connection class code:
class databaseConnection {
//Database information
protected $mysqliUser = "";
protected $mysqliHost = "localhost";
protected $mysqlipass = "";
protected $mysqlidbname = "";
public $con;
public function __construct() {
$this->con = new mysqli($this->mysqliHost,$this->mysqliUser,$this-
>mysqlipass,$this->mysqlidbname);
}
}
A snippet of the class code that is receiving the error:
private $conn;
$conn = new databaseConnection;
Any help to point me in the right direction is much appreciated.

above the private declaration is just the class creation class
createSession
In which case your $conn = new databaseConnection; either needs visibility, or should be in a method. Hard to tell which without seeing all the class and the odd indentation you have.
So put that in the method it belongs in (perhaps the constructor?) or set it to private, protected, or public - whichever it was intended for.

Check this out.
It really works..
connect.php
class DBConnect {
private static $connection;
private static $host = "localhost";
private static $user = "root";
private static $pwd = "";
private static $dbname = "yourDBName";
public static function connect() {
$host = self::$host;
$user = self::$user;
$pwd = self::$pwd;
$dbname = self::$dbname;
self::$connection = new mysqli($host, $user, $pwd, $dbname) or die('Error connecting..');
return self::$connection;
}
}
myclass.php
require_once('connect.php');
class MyClass {
private $connObj;
public function __construct() {
$this->connObj = DBConnect::connect();
}
public function select() {
$conn = $this->connObj;
$sql = "SELECT * FROM table_name";
$query = $conn->query($sql);
$res = $query->fetch_assoc();
// your code..
}
}
$obj = new MyClass();
$obj->select();
Hope, this code snippet works fine for you. :) :)

Related

Getting query error in OOP php

I'm just new using OOP php and I'm having a hard time to figure out how to query in database using class method. Here's my code and I've got an error which I dont know how to solve.
I declared the connection variable but I don't know why it's undefined
Notice: Undefined variable: connection
Fatal error: Call to a member function query() on a non-object in
db.php
class DbConnector {
private $serverName;
private $userName;
private $password;
private $dbName;
private $connection;
public function __construct(){
$this->serverName = "localhost";
$this->userName = "root";
$this->password = "attl";
$this->dbName = "oop";
$this->connection = new mysqli($this->serverName, $this->userName, $this->password, $this->dbName);
if ($this->connection->connect_error) {
$this->connection = die("Connection failed: " . $this->connection->connect_error);
}
}
public function getConnection(){
return $this->connection;
}
}
index.php
include('../queries/db.php');
class Users{
private $connection;
public function __construct(){
$con = new DbConnector();
$connection = $con->getConnection();
}
public function getUsers(){
$sql = $connection->query("SELECT * FROM login");
while($getUsers = $sql->fetch_array()){
echo $getUsers['username'];
}
}
}
$user = new Users();
return $user->getUsers();
Your problem is you're trying to access a locally scoped variable rather than a class property
public function getUsers(){
$sql = $connection->query("SELECT * FROM login"); // HERE
while($getUsers = $sql->fetch_array()){
echo $getUsers['username'];
}
}
this can't find a variable called $connection in that scope, you need to access the object property using $this.
class Users {
private $connection;
public function __construct()
{
$con = new DbConnector();
// Assign this to object propety declared above
$this->connection = $con->getConnection();
}
public function getUsers()
{
// now access the object property set in constructor.
$sql = $this->connection->query("SELECT * FROM login");
while($getUsers = $sql->fetch_array()){
echo $getUsers['username'];
}
}
}
Since you're declaring the following as private:
private $connection;
and including it in your construct:
public function __construct(){
$con = new DbConnector();
$connection = $con->getConnection();
You need to use $this for its property:
$this->connection = $con->getConnection();
Then changing:
$sql = $connection->query
to
$sql = $this->connection->query
in order to use the connection property.
Now, I have to admit that I am not an OOP expert and there may be another way to have solved this, yet this is what I took from it, which worked for me.

Assigning value of static variable to a class variable

Config.php
class Config {
public static $dbserver = "hostedserverURL";
}
DB.php
require 'Config.php'
class DB {
private $server = Config::$dbserver; // compile-error
private $user = "user";
private $password = "password";
private $database = "databasename";
private $db;
}
compile-error says "syntax error, unexpected '$dbserver', expecting 'identifier' or 'class'"
If I remove the $ and change the line to private $server = Config::dbserver; , the compile-error is gone. but this is not correct.
I get a Runtime error in that case.
Fatal error: Undefined class constant 'Config::dbserver' in ..
So I have to retain the $ , Also as per this SO thread: Fatal error: Undefined class constant
This is where I am making use of it,
public function __construct()
{
$this->db = new PDO(
"mysql:host={$this->server};dbname={$this->database};charset=utf8",
$this->user,
$this->password
);
return $this;
}
Question: How can I refer the static variable dbserver and make that as default value for $server of class DB ? Any ideas please
You can not assign variables in classes from functions and other classes or non-trivial expressions until 5.6. You will have to set the variable using a function within the class.
For now type in php -v into your terminal to see what version you are using. Otherwise if you want to use that functionality, upgrade PHP to PHP 5.6
https://wiki.php.net/rfc/const_scalar_exprs
This is a php (version < 5.6) limitation, however you can simply initialize the properties in the constructor:
class DB
{
private $server;
private $user;
private $password;
private $database;
private $db;
public function __construct()
{
$this->server = Config::$dbserver; // No compile-error
$this->user = "user";
$this->password = "password";
$this->database = "databasename";
$this->db = new PDO(
"mysql:host={$this->server};dbname={$this->database};charset=utf8",
$this->user,
$this->password
);
//return $this; no need for this
}
}
Or upgrade to a later (5.6+) version of php.
Also, from a design perspective, having the various variables hard-coded and scattered over 2 files is needlesy complicated. Ideally have them all injected in the constructor:
public function__construct($server, $user, $password, $database)
{
$this->server = $server;
$this->user = $user;
//etc
}
failing that have them all declared in the config class:
public function__construct()
{
$this->server = Config::$server;
$this->user = Config::$user;
//etc
}
You can't use variables from outside the class, even if you require them in the same file.
You could do this:
class DB {
private $server;
private $user = "user";
private $password = "password";
private $database = "databasename";
private $db;
public function __construct(){
require 'Config.php';
$this->server = Config::$dbserver; //Will set the $server variable of the instantiated class.
}
}

Object oriented CRUD with Mysqli

I'm trying to learn OOP programming in PHP. So far i got couple of basic things but i don't know how to echo my results into the page. I made up Database class and Category class i wanna echo the results from read function but i don't know how to do that. Can someone help me refactor this so i can use both classes?
This is my code
class Database {
private $_connection;
private $_host = "localhost";
private $_username = "root";
private $_password = "";
private $_database = "cmsi";
// Conect to database is private and can only be used by getConection function result is returned object of mysqli class
//can be seen in var_dump() function
private function conect() {
//$this refers to class Database and her functions and propertys are being acsessed via -> sign
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()) {
trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
E_USER_ERROR);
}
return $this->_connection;
}
//Safest way to iniate conection
public function getConection(){
return $this -> conect();
}
}
class Category{
private $db_sql;
public function __construct($db){
$this->db_sql = $db;
}
public function read(){
$conection = $this->db_sql;
$query = "Select * from category";
$result = $conection -> query($query);
return $result;
}
}
$db = new Database();
$conection = $db->getConection();
$obj = new Category($conection);
$obj->read();
You're almost there. Just store the result set in a variable and loop through it, like this:
// your code
$db = new Database();
$conection = $db->getConection();
$obj = new Category($conection);
// store the result set
$result_set = $obj->read();
// loop through the result set
while($row = $result_set->fetch_array()){
// your code
}

How to properly use dependency injection with PHP?

I'm very new at PHP. I have two classes: Database and RetrieveItem. Because RetrieveItem needs a connection, I've just been extending the Database class to use its constructor. Apparently this is wrong, because RetrieveItem is not a database?
Here is my current code:
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem extends Database {
function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
And on a separate page, to use this, I have:
include 'db.php';
$retrieve = new RetrieveItem();
print_r($retrieve->retrieve_item());
Rather than extend the class, how can I access the Database constructor in the cleanest possible way?
Any help or guidance would be much appreciated.
This amended code is still not working:
Argument 1 passed to RetrieveItem::__construct() must be an instance of Database, none given:
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem {
private $_db;
public function __construct(Database $database){
$this->_db = $database;
}
public function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
In use:
include 'db.php';
$database = new Database();
$retrieve = new RetrieveItem($database);
print_r($retrieve->retrieve_item());
As you said, with plain dependency injection
class RetrieveItem {
private $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
For easier use, you can abstract the injection in container, or, at least, has one super class that recieves the injection.
A dependency injection is so easy but it sounds complicated.
$class1 = new firstclass();
$class2 = new secondclass($class1); //This is a dependency injection.
class firstclass{
private $var1;
private $var2;
public function __construct(){
$this->var1 = "hello";
$this->var2 = "world";
}
public function getvar1(){
return $this->var1;
} //imagine a second one like this for var2;
}
class secondclass{
private $fc; //will hold first class object or the dependency.
public function __construct($firstclassobject){
$this->fc = $firstclassobject;
echo $this->fc->getvar1(); //call dependency methods like this.
echo $this->fc->getvar2();
} //echoes helloworld
}
So you pretty much put an object of one class and asign it to a field in your other class.
for your edit
set this line in your database class at the top.
public connect; //add to dbclass
Then do this in your function
public function retrieve_item(){
$connect = $this->db->connect; //added this
$query = $connect->prepare("SELECT * FROM posts"); //changed this
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
public $connect;
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem {
private $connect;
public function __construct(&$db){
$this -> connect = $db -> connect;
}
function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
// Usage
$db = new Database();
$retrieve_item = new RetrieveItem($db);
Here in Retrieve Item we tried to send the database object as a refereneced variable rather sending a copy of its, which happens to be a good way of passing connection to your operable classes

PHP - PDO Connection Class - Unable To Access

I'm currently writing my first PHP application using OOP and PDO. In doing so I'm working on a connection class so that I can initiate a database connection when needed. I believe the terms for the way I am doing it is dependency injection.
I currently have an error when trying to access the connection.
This is my connection class:
class db{
private $host = '';
private $dbname = '';
private $username = '';
private $password ='';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We have a problem!';
}
}
}
And this is how I am trying to call it inside of other classes.
private $con;
public function __construct(db $con) {
$this->con = $con;
}
However this is the error I receive when trying to run it.
Catchable fatal error: Argument 1 passed to users::__construct() must be an instance of db, none given.
Any advice on what I am doing incorrectly would be much appreciated.
You will need to first create your DB instance and pass it to the constructor of your 'Other' class
$db = new DB();
$class = new OtherClass($db);
Apart from that, there are other issues:
The DB class constructor did not assign values to the database name, user and password etc. One way of doing it is to pass those settings to the constructor of DB and assign the values to the private properties.
class DB{
private $host = '';
private $dbname = '';
private $username = '';
private $password ='';
public $con = '';
function __construct($host, $dbname, $username, $password){
$this->host = $host;
$this->dbname = $dbname;
$this->username = $username;
$this->password = $password;
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We have a problem!';
}
}
}

Categories