How to use the instance of DB class inside functions? - php

This is my DB class. (DB.php)
<?php
class DB {
protected $db_name = "data_db";
protected $db_user = "root";
protected $db_pass = "root";
protected $db_host = "localhost";
public function __construct() {
$this->mysqli = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
}
public function __destruct() {
$this->mysqli->close();
}
}
?>
This is my users.php file.
<?php
require_once "core/DB.php";
function user_data() {
global $db;
$db = new DB();
$data = array();
$session_user_id = $_SESSION["user_id"];
$data_row = $db->mysqli->query("SELECT * FROM `users` WHERE `user_id` = '$session_user_id'");
$data = $data_row->fetch_assoc();
return $data;
}
?>
How can I use the $db instance of DB class inside my functions?
Should I call the instance only once and than make it a global variable to use in all functions?

pleeeeaaase, don't use global variables
try it with a singleton pattern
class DB {
protected $db_name = "data_db";
protected $db_user = "root";
protected $db_pass = "root";
protected $db_host = "localhost";
public static function getInstance()
{
static $instance = null;
if (is_null($instance)) {
$instance = new DB();
}
return $instance;
}
public function __construct() {
$this->mysqli = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
}
public function __destruct() {
$this->mysqli->close();
}
}
in your functions you can use it than this way
function user_data() {
$db = DB::getInstance();
$data = array();
$session_user_id = $_SESSION["user_id"];
$data_row = $db->mysqli->query("SELECT * FROM `users` WHERE `user_id` = '$session_user_id'");
$data = $data_row->fetch_assoc();
return $data;
}
just call DB::getInstance() to get all time the same instance of your class

Related

Can't connect to database by calling function in class using PHP

I'm stuck in that situation that when I use $this->conn it returns:
Uncaught Error: Using $this when not in object context
but if I don't use it, then it said:
Undefined variable: conn
class save extends forma
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'world';
public $conn;
protected $table;
private function __construct()
{
if (!$this->table)
die('No table name provided');
}
function connect()
{
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($conn->connect_error) {
die($this->conn->connect_error);
}
return $this->conn;
}
public function saugoti($id,$pakeitimui=0, $kas=0)
{
$this->connect();
if(isset($_POST['saugoti']))
{
$table = "bmp_test";
$id = $_POST['id'];
$pav = $_POST['pav'];
$adr = $_POST['adr'];
$tel = $_POST['tel'];
if ($pakeitimui == 0)
{
$sql1 = "SHOW FIELDS FROM $table ";
$result = $conn->query($sql1);
You want to use the class variable $conn everywhere (this will be written as $this->conn) instead of $conn (which is a local variable).
Replacing all occurences of $conn by $this->conn in your code will solve that problem.
The main reason it was not working is you are using $this->conn->connect_error in connect function while storing connection in $conn which is local variable and not class variable
If you dont want to call $this->connect(); in every function then below code might work for you
class save extends forma
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'world';
public $conn;
protected $table = 'test_table';
public function __construct()
{
if (!$this->table)
die('No table name provided');
$this->connect();
}
function connect()
{
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die($this->conn->connect_error);
}
return $this->conn;
}
public function saugoti($id,$pakeitimui=0, $kas=0)
{
if(isset($_POST['saugoti']))
{
$table = "bmp_test";
$id = $_POST['id'];
$pav = $_POST['pav'];
$adr = $_POST['adr'];
$tel = $_POST['tel'];
if ($pakeitimui == 0)
{
$sql1 = "SHOW FIELDS FROM $table ";
$result = $this->conn->query($sql1);

Setting PHP Class variable with a variable call

I am modifying a script that I bought and I am having trouble making the Database name variable that is set in the Database class be the result of the variable I construct above it. I need the $dbName variable to be set to the combination of "mmo_" appended to the variable $username that I get from my database. The name of the database should be "mmo_school" with school being the $username variable that is pulled from database. However, it fails unless I put the text of the variable in single quotes after $dbName = . But I need the database name to be dynamically set based on which user is using the script. I hope that this makes sense and I really appreciate your help!!
$username = "school";
$newname = "mmo_" . $username; **// the results of this would be "mmo_school"**
class Database
{
private static $dbName = $newname ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
public function __construct() {
exit('Init function is not allowed');
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
if I type in $dbName = 'mmo_school' ; THIS WORKS.
if I try to use the variable I create as shown above...IT DOESN'T!!!
THANKS FOR YOUR HELP!!
Create a public static method to set the host, username, password, and etc. Also, i would change your constructor to private not public.
Database::setDB('mmo_' . $username);
// or
Database::setConnectInfo('mmo_' . $username, 'some host', $username, 'some password');
$db = Database::connect();
class Database
{
private static $dbName = $newname ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
private function __construct() {
exit('Init function is not allowed');
}
public static function setDB($dbName){
self::$dbName = $dbName;
}
// or use this function
public static function setConnectInfo($dbName, $dbHost, $dbUsername, $dbUserPassword){
self::$dbName = $dbName;
self::$dbHost = $dbHost;
self::$dbUsername = $dbUsername;
self::$dbUserPassword = $dbUserPassword;
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
In your class you have to call $newname as a global variable. With this minor change your code should work.
$username = "school";
$newname = "mmo_" . $username; **// the results of this would be "mmo_school"**
class Database {
private static $dbName = "" ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
function __construct($init_parameter) {
global $newname;
$this->$dbName = $newname;
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
because single quotes don't do variable expansion - use double quotes
$var = 'dingo';
$name = 'xyz_$var'; // result 'xyz_$var'
$name = "xyz_$var"; // result 'xyz_dingo'

OOP MySQLi Connect

Im newbie in OOP. I have class Database
class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;
function db_connect(){
$this->host = 'localhost';
$this->user = 'root';
$this->pass = '';
$this->db = 'db';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->mysqli;
}
Inside class Database i have function db_num
function db_num($sql){
$num = mysqli_num_rows(mysqli_query($this->mysqli,"{$sql}"));
return $num;
}
But it cant connect to database when im using in con argument $this->mysqli
It is bad practice to mix mysqli object style and procedural style.
Try this:
function db_num($sql){
$result = $this->mysqli->query($sql);
return $result->num_rows;
}
Be sure to connect to the database before you call db_num(), e.g.:
$db = new Database();
$db->db_connect();
$db->db_num("SELECT fields FROM YourTable");
A cleaner way in my opinion would be to call db_connect inside the constructor:
class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;
public function __construct() {
$this->db_connect();
}
private function db_connect(){
$this->host = 'localhost';
$this->user = 'root';
$this->pass = '';
$this->db = 'db';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->mysqli;
}
public function db_num($sql){
$result = $this->mysqli->query($sql);
return $result->num_rows;
}
}
$db = new Database();
$db->db_num("SELECT fields FROM YourTable");
<?php
/**
* Creating a class for the database connection
* To start using the database connection like this: $database = DatabaseFactory::getFactory()->getConnection();
*/
class DatabaseFactory {
protected $servername = "servername";
protected $username = "root";
protected $password = "root";
protected $dbname = "databasename";
private static $factory;
private $database;
public static function getFactory() {
if(!self::$factory) {
self::$factory = new DatabaseFactory();
}
return self::$factory;
}
public function getConnection() {
if(!$this->database) {
try {
$this->database = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
} catch (mysqli_sql_exception $e) {
$error = $e->getMessage();
echo "Error:" .$error;
exit;
}
}
return $this->database;
}
}

php oops including another page

Here is my code in database.php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "ss";
$con = new PDO('mysql:host=localhost;dbname=app', $db_username, $db_pass);
In my class page
include_once "database.php";
class article_fun
{
public function myfun()
{
$sqlcreate = $con->query("selct query")
}
}
How do we do we use $con->query("select query") getting an error Undefined variable: con how to fix this?
use this
class article_fun
{
private $con;
public function __construct($con){
$this->con=$con;
}
public function myfun()
{
$sqlcreate = $this->con->query("selct query")
}
}
call this
include_once "database.php";
new article_fun($con);
or use this
class article_fun
{
private $con;
public function __construct(){
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "ss";
$this->con = new PDO('mysql:host=localhost;dbname=app', $db_username, $db_pass);
}
public function myfun()
{
$sqlcreate = $this->con->query("selct query")
}
}
Pass$con as a parameter to article_fun::myFun()
class article_fun
{
public function myfun($con)
{
$sqlcreate = $con->query("selct query")
}
}
FYI, in PHP it is convention to start class names with a capital letter and use camelCase:
class ArticleFun
Your created variables are outside of the function scope.
So you can't access variables outside a function from inside the function.
Try to use the magic function __construct()
Like this:
class article_fun{
private $_con;
public function __construct( $con ){
$this -> _con = $con;
};
public function myfun(){
$sqlcreate = $this -> _con->query("selct query")
}
}
Now you just have to pass the $convar to the Class like so:
$article_fun = new article_fun( $con );
class article_fun
{
public function myfun()
{
global $con;
$sqlcreate = $con->query("select query")
}
}
Your variable is definied in the global context and you try to use it in a method of a class.
Use global variable
$GLOBALS['con'] = $yourConnection;
Check this link for answer
How to declare a global variable in php?

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

Categories