I had 2 Class in PHP That i want to use with each other, but the Class in 2 different PHP Script like clothing_product.php and database.php. It look like this Below:
database.php:
require_once('config.php');
class MySqlDatabase
{
private $connection;
private $last_query;
private $magic_quotes_active;
private $real_escape_string_exist;
function __construct(){
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exist = function_exists("mysql_real_escape_string");
}
private function open_connection()
{
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$this->connection){
die("Connection failed!". mysql_error());
}
else{
$db_select = mysql_select_db(DB_NAME);
if(!$db_select){
die("Select database failed". mysql_error());
}
}
}
public function query($sql){
$this->last_query = $sql;
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function confirm_query($result){
if(!$result){
$output = "Database query failed: " . mysql_error()."<br /><br />";
$output.= "Last query that fail is:" . $this->last_query;
die($output);
}
}
private function escape_value($value) {
if ($this->real_escape_string_exist) {
if($this->magic_quotes_active) {$value = stripslashes($value);}
$value = mysql_real_escape_string($value);
}
else {
if (!$this->magic_quotes_active) {$value = addslashes($value);}
}
return $value;
}
public function fect_array($result){
return mysql_fetch_array($result);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function last_id(){
return mysql_insert_id($this->connection);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
}
//$db = new MySqlDatabase();
clothing_product.php:
include('../database.php');
class Clothing_Product {
public $db = new MySqlDatabase();
public static function test(){
echo "Static call successfull";
return "Static call successfull";
}
}
The problem is when i try to USE 'Public $db = new MySqlDatabase();' in class clothing_product i get Error. I think the problem is maybe i got a wrong call. Please help me cuz m a noob thnk.
You can't initialize member variables to anything that is not static, and you're trying to create an object here:
public $db = new MySqlDatabase();
From the manual:
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 workaround is to set your variable in the constructor:
public $db;
public function __construct() {
$this->db = new MySqlDatabase();
}
Related
I am trying to get all value from database using PHP Object method and getting error:
Fatal error: Uncaught Error: Call to undefined method
Calldb::mysqli_query() in
C:\xampp\htdocs\geomaticxpms\core\Alltablevalue.php:13
Stack trace: 0 C:\xampp\htdocs\geomaticxpms\manager\header.php(8):
Alltablevalue-
Getallvalue('business')
1 {main} thrown in C:\xampp\htdocs\geomaticxpms\core\Alltablevalue.php on line 13
I have custom auto loader file which bring all files calling through a PHP include function
I am connecting database using (Calldb.php):
class Calldb {
public $db;
public function __construct() {
require_once('config.db.php');
$this->db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABSE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
public function __destruct() {
mysqli_close($this->db) OR die("There was a problem disconnecting from the database.");
}
}
Get all table data (Alltablevalue.php):
class Alltablevalue {
public $db;
public $table;
public $data;
function __construct($db)
{
$this->db = $db;
}
function Getallvalue($table){
$this->table = $table;
$data = $this->db->mysqli_query("SELECT * FROM $this->table");
if($data->num_rows > 0){
$row = $connect->fetch_assoc();
return $this->$row;
}
else { return false;}
}
}
Output page:
include_once('functions.php');
if (!$including) exit("direct access not permitted");
//echo "<pre>";
$db = new Calldb();
$connect = new Alltablevalue($db);
$data = $connect->Getallvalue("business"); // "business" is table name
Please guide so I can make it work.
I will provide all description if need.
auto-loader class file calling through functions.php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
everyone thank you for your help. I there was mistake in my code:
Problem in "Alltablevalue.php"
class Alltablevalue {
public $db;
public $table;
public $data;
function __construct($db)
{
$this->db = $db;
}
function Getallvalue($table){
$this->table = $table;
$data = $this->db->db->query("SELECT * FROM $this->table");
if($data->num_rows > 0){
$row = $data->fetch_assoc();
return $row;
}
else { return false;}
}
}
this code works:
if (isset($db->error)) {
echo $db->error;
}
This code in not working:
if (isset($db->error)) {
die($db->error);
}
This is my DB class:
class Db {
private $db,
$error;
public function __construct() {
return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
if ($this->db->connect_error) {
$this->error = $this->db->connect_error;
}
}
}
"D_NAME" is wrong so an error appears but I didn't kill the page, content still appear after the error. Why? Thanks!
The if block in the constructor is never executed, because you are returning $this->db:
public function __construct() {
return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
// the lines after return will never be executed!
}
This is the first reason why the $db->error is unset.
The second reason is that the $error member is private, which means that you are not allowed to access this property directly. So you should make it accessible in one of the following ways (at least):
make it public;
implement the __get and __isset magic methods;
implement a getter method.
Using public $error
class Db {
private $db;
public $error;
public function __construct() {
$this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
if ($this->db->connect_error) {
$this->error = $this->db->connect_error;
}
return $this->db;
}
}
$db = new Db;
if (isset($db->error)) {
die($db->error);
}
echo 'xxx', PHP_EOL;
Using __isset and __get magic methods
class Db {
private $db;
private $error;
public function __construct() {
$this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
if ($this->db->connect_error) {
$this->error = $this->db->connect_error;
}
return $this->db;
}
public function __get($key) {
if ($key === 'error') {
return $this->error;
}
}
public function __isset($key) {
if ($key === 'error') {
return isset($this->error);
}
}
}
$db = new Db;
if (isset($db->error)) {
die($db->error);
}
echo 'xxx', PHP_EOL;
Implementing a getter method
A getter method is just a method returning value of a private member. In our case it is $error. So you might leave it private, but add a method to access its value. For instance:
public function getError() {
return $this->error;
}
I don't understand why I remove code in line 14($this->close();), it don't have error but i don't remove it then it warning mysqli_query(): Couldn't fetch mysqli. It is at the end construct ???
My error: enter image description here
My code:
<?php
class Display extends Awebarts
{
private $conn;
private $tablename;
public function __construct($tablename)
{
$this->tablename = $tablename;
$this->connectToDb();
$this->conn = $this->getConn();
// insert the data into the table
$this->getData();
$this->close();
}
function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY `id` DESC LIMIT 1 ";
if(!$sql = mysqli_query($this->conn, $query)) {
throw new Exception("Error: Can not excute the query.");
} else {
$num = mysqli_num_rows($sql);
while($num > 0) {
//var_dump($data);
$data = mysqli_fetch_array($sql);
$num--;
}
}
return $data;
}
}
class Awebarts
{
private $cxn;
private $conn;
function connectToDb()
{
include "models/Database.php";
$vars = "include/vars.php";
$this->cxn = new Database($vars);
$this->conn = $this->cxn->getConn();
}
function getConn()
{
return $this->conn;
}
function close()
{
$this->cxn->close();
}
}
class Database
{
private $host;
private $user;
private $password;
private $database;
private $conn;
function __construct($filename)
{
if(is_file($filename)) {
include $filename;
} else {
throw new Exception("Error");
}
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->connect();
$this->selectData();
}
function getConn()
{
return $this->conn;
}
private function connect()
{
// connect to the sercer
if(!mysqli_connect($this->host, $this->user, $this->password)) {
throw new Exception("Error: not connected to the server");
} else {
$this->conn = mysqli_connect($this->host, $this->user, $this->password);
}
return $this->conn;
}
private function selectData()
{
if(!mysqli_select_db($this->conn, $this->database)) {
throw new Exception("Error: No database");
}
}
function close()
{
mysqli_close($this->conn);
}
}
?>
The problem is that the connection is closed when you call getData() after you have created the Display object.
The getData() call in your constructor doesn't make any sense, because you don't use/save the return value. So when then constructor is executed you open a connection, send a select query (which return value you don't save) and then close the connection. After that a getData() call results in your error message.
You can either save the result of your getData() call from the constructor in a private field and access it later or remove the getData() and $this->close(); call from the constructor and call them from outside.
Try to perform method Database::connect like this:
private function connect()
{
// connect to the sercer
if(!$connect = mysqli_connect($this->host, $this->user, $this->password)) {
throw new Exception("Error: not connected to the server");
}
$this->conn = $connect;
return $this->conn;
}
I am a newbie to OOP. I have worked in procedural programming a lot. So i am in little trouble right now. Can you please tell me how to call an object of a class in another class and then i can access all the variables and function of that class with using that object.
For e.g
I have a class of DBconnection. i write my db queries in it. Now i have an other class named Users. Now i need to access the db queries in User class, definitely i need object of DBconnection class to access all db queries. What can i do please help
The example code which i have written is as below:
**DBConnection class**
class DBConnection
{
public $SITEURL;
public $servername;
public $username;
public $password;
public $dbname;
public $objDbConnect;
function DBConnection(){
$this->SITEURL=Configuration::SITEURL;
$this->servername=Configuration::servername;
$this->username=Configuration::username;
$this->password=Configuration::password;
$this->objDbConnect=mysql_connect($this->servername,$this->username,$this->password);
if($this->objDbConnect){
mysql_select_db($this->dbname);
}
}
function InsertRecord($pStrTableName,$pArrField,$pArrValue)
{
$strSql="insert into $pStrTableName (";
$intFieldSize=count($pArrField);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.=$pArrField[$i];
}
else
{
$strSql.=$pArrField[$i].",";
}
}
$strSql.=") values (";
$intFieldSize=count($pArrValue);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.="'".$pArrValue[$i]."'";
}
else
{
$strSql.="'".$pArrValue[$i]."'".",";
}
}
$strSql.=")";
if(mysql_query($strSql))
{
return 1;
}
else
{
return 0;
}
}
}
**Users class**
class Users{
var $username,
$userpassword,
$email,
function User(){
}
}
The best way to do this would be to use Singleton pattern.
Following is an example
class DBConnection
{
private static $instance = null;
private function __construct() {
}
/*
* #return DBConnection
*/
public static function get_db()
{
if ( empty(self::$instance) ) self::$instance = new DBConnection();
return self::$instance;
}
public function query()
{
}
}
class User
{
function testfunc()
{
$db = DBConnection::get_db();
$db->query();
}
}
You can declare an object of your class in your second class and use it like
$c= new DBConnection();
$c->InsertRecord('Parameters here etc');
echo $c->username; //and other public variables similarly
DBConnection class
class DBConnection
{
public $SITEURL;
public $servername;
public $username;
public $password;
public $dbname;
public $objDbConnect;
function DBConnection(){
$this->SITEURL=Configuration::SITEURL;
$this->servername=Configuration::servername;
$this->username=Configuration::username;
$this->password=Configuration::password;
$this->objDbConnect=mysql_connect($this->servername,$this->username,$this->password);
if($this->objDbConnect){
mysql_select_db($this->dbname);
}
}
function InsertRecord($pStrTableName,$pArrField,$pArrValue)
{
$strSql="insert into $pStrTableName (";
$intFieldSize=count($pArrField);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.=$pArrField[$i];
}
else
{
$strSql.=$pArrField[$i].",";
}
}
$strSql.=") values (";
$intFieldSize=count($pArrValue);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.="'".$pArrValue[$i]."'";
}
else
{
$strSql.="'".$pArrValue[$i]."'".",";
}
}
$strSql.=")";
if(mysql_query($strSql))
{
return 1;
}
else
{
return 0;
}
}
}
Users class
class Users{
var $username;
var $userpassword;
var $email;
var $dbcon;
public function __construct()
{
//create an object
$this->dbconn = new DBConnection();
//get user name from dbconnection class
echo $this->dbconn->username;
}
function User(){
}
}
//create object for user class
$user = new User();
**DBConnection class**
class DBConnection
{
public $SITEURL;
public $servername;
public $username;
public $password;
public $dbname;
public $objDbConnect;
function DBConnection(){
$this->SITEURL=Configuration::SITEURL;
$this->servername=Configuration::servername;
$this->username=Configuration::username;
$this->password=Configuration::password;
$this->objDbConnect=mysql_connect($this->servername,$this->username,$this->password);
if($this->objDbConnect){
mysql_select_db($this->dbname);
}
}
public static function getConnection(){
if(!empty($this)){
return $this;
}
return new DBConnection();
}
function InsertRecord($pStrTableName,$pArrField,$pArrValue)
{
$strSql="insert into $pStrTableName (";
$intFieldSize=count($pArrField);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.=$pArrField[$i];
}
else
{
$strSql.=$pArrField[$i].",";
}
}
$strSql.=") values (";
$intFieldSize=count($pArrValue);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.="'".$pArrValue[$i]."'";
}
else
{
$strSql.="'".$pArrValue[$i]."'".",";
}
}
$strSql.=")";
if(mysql_query($strSql))
{
return 1;
}
else
{
return 0;
}
}
}
**Users class**
class Users{
var $username,
$userpassword,
$email,
function User(){
$db = DBConnection::getConnection();
$db->InsertRecord($x, $x, $x);
}
}
1 . You can change your class DBConnection to singleton. And call your class in User like this DBConnection::getInstance()->InsertRecord(...). It's easy. But not recommended.
2 . You can push your DBConnection instance inside User. Like this
class Users{
var $db_connection;
function __construct($db_connection){
$this->db_connection = $db_connection;
}
$db_connection = new DBConnection(...);
$user = new User($db_connection);
3 . You can instantiate new DBCOnnection inside User class. Like in #Sundar answer.
P.S. Do not use old construct style.
You can keep a reference to the DBConnection in your User class (pass it in in the constructor).
private $dbConn;
function __contruct($dbConnRef) {
$this->dbConn = $dbConnRef;
}
public function storeSelf() {
$this->dbConn->InsertRecord(...);
}
In my project I have a database class that I use to handle all the MySQL stuff. It connects to a database, runs queries, catches errors and closes the connection.
Now I need to create a members area on my site, and I was going to build a users class that would handle registration, logging in, password/username changes/resets and logging out. In this users class I need to use MySQL for obvious reasons... which is what my database class was made for.
But I'm confused as to how I would use my database class in my users class. Would I want to create a new database object for my user class and then have it close whenever a method in that class is finished? Or do I somehow make a 'global' database class that can be used throughout my entire script (if this is the case I need help with that, no idea what to do there.)
Thanks for any feedback you can give me.
Simple, 3 step process.
1/ Create a database object.
2/ Give it to your user class constructor.
3/ Use it in the user methods.
Little example.
File Database.class.php :
<?php
class Database{
public function __construct(){
// Connects to database for example.
}
public function query($sqlQuery){
// Send a query to the database
}
[...]
}
In User.class.php :
<?php
class User{
private $_db;
public function __construct(Database $db){
$this->_db = $db;
}
public function deleteUser(){
$this->_db->query('DELETE FROM Users WHERE name = "Bobby"');
}
}
Now, in userManager.php for example :
<?php
$db = new Database();
$user = new User($db);
// Say bye to Bobby :
$user->deleteUser();
If you want the current trendy name of this old technique, google "Dependency Injection". The Singleton pattern in php will fade away soon.
As he said, put all your functions in the database class and use the database object to access those functions from your user class. This should be the best method in your case.
Eg:
global $database;
userclassvar = $database->doSomething();
What I like to do is make the database class with the Singleton pattern in mind. That way, if you already have a database object, it just retrieves it, otherwise creates a new one. For example:
Database.class.php
class Db
{
protected static $_link;
private function __construct()
{
// access your database here, establish link
}
public static function getLink()
{
if(self::_link === null) {
new Db();
}
return self::_link;
}
// etc.
}
User.class.php
class User
{
protected $_link; // This will be the database object
...
public function __construct()
{
$this->_link = Db::getLink();
}
}
And now you can use User's $_link property to do the database functions, like $this->_link->query(...). You don't necessarily have to put the Db::getLink() in the constructor if your class doesn't have to interact with the database that much.
Since you are using the database as an object, why not just add methods to the object that your "users class" can employ to take care of the things it needs to do. The users class can contain a pointer to the database class. The database class will protect your database, and assure that the users class is using it appropriately.
Here is a solution using PDO.
<?php
class Database {
private static $dbh;
public static function connect() {
$host = "mysql:dbname=YOUR_DB_NAME;host=YOUR_DB_SERVER";
$username = "YOUR_USERNAME";
$password = "YOUR_PASSWORD";
try {
self::$dbh = new PDO( $host, $username, $password );
self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch( PDOException $e ){
$error_message = $e->getMessage();
exit();
}
return self::$dbh;
}
}
class MYObject {
public static $dbh = null;
public function __construct(PDO $db = null) {
if($db === null){
$this->dbh = Database::connect();
} else {
$this->dbh = $db;
}
}
}
class User extends myObject {
public function __construct($id = null, PDO $db = null) {
if($db === null){
parent::__construct();
} else {
parent::__construct($db);
}
if($id !== null){
return $this->select($id);
}
}
public function select($id) {
$retVal =false;
try {
$stmt = $this->dbh->prepare("SELECT...");
$stmt->execute();
if( $stmt->rowCount()==1 ){
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$retVal =json_encode($row);
}
} catch (PDOException $e ) {
$error_message = $e->getMessage();
exit();
}
return $retVal;
}
}
?>
I think the better aproach would be to create the database class that instatiate right away on its own on a database.php and then include it on user.php. then every time you create a function that needs a database, you globalise the database object.
Check this.
databse.php
<?php
require_once ('includes/config.php');
class MysqlDb{
public $connection;
private $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
public function __construct() {
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists( "mysql_real_escape_string" );
}
public function open_connection() {
$this->connection = mysql_connect(DBHOST,DBUSER,DBPASS);
if(!$this->connection){
die("Could not Connect ".mysql_error());
}else{
$db = mysql_select_db(DB, $this->connection);
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$this->last_query = $sql;
$results = mysql_query($sql, $this->connection);
$this->comfirm_query($results);
return $results;
}
private function comfirm_query($results){
if(!$results){
$output = "Query Failed " .mysql_error()."<br />";
$output .= "Last Query: " . $this->last_query;
die($output);
}
}
public function escape_value($value){
if( $this->real_escape_string_exists ) {
if($this->magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
} else {
if( !$this->magic_quotes_active ) { $value = addslashes( $value ); }
}
return $value;
}
public function fetch_array($results){
return mysql_fetch_array($results);
}
public function num_row($results){
return mysql_num_rows($results);
}
public function insert_id(){
return mysql_insert_id($this->connection);
}
public function affected_row(){
return mysql_affected_rows();
}
}
$database = new MysqlDb();
?>
here is the user.php
<?php
require_once ('includes/database.php');
class User {
public $id;
public $fName;
public $lName;
Public $userName;
public $password;
public $email;
public $acess;
public static function find_all(){
global $database;
return self::find_by_sql("SELECT * FROM users");
}
public static function find_by_id($id=0){
global $database;
$results_array = self::find_by_sql("SELECT * FROM users where id={$id}");
return !empty($results_array)? array_shift($results_array) : false;
}
public static function find_by_sql($sql){
global $database;
$results = $database -> query($sql);
$object_array = array();
while($row = $database -> fetch_array($results)){
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function instantiate($row){
$user = new self;
foreach($row as $attribute => $value){
if($user -> has_attribute($attribute)){
$user -> $attribute = $value;
}
}
return $user;
}
private function has_attribute($attribute){
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>