OOP MySQLi Connect - php

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;
}
}

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);

PHP pass values from php file to other class

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)
{
//....
}

how to call php pdo connection class in another page

I created a connection in db.php class like this:
class db
{
public $isConnected;
protected $database;
public function __construct($username, $password, $host, $dbname, $options=array())
{
$this->isConnected = true;
try {
$this->database= new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$this->database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->database->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function select($query, $params=array()){
try{
$stmt = $this->database->prepare($query);
$stmt->execute($params);
return $stmt->fetch();
}catch(PDOException $e){
throw new Exception($e->getMessage());
}
}
}
and I am accessing this class in state.php page like this:
<?php
$database = new db("root", "", "localhost", "bhaskar_hindi_dbs", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$getrows = $database->select("SELECT state_id, state_name FROM state");
foreach($getrows as $row){
?>
but I have multiple pages in my project. Now I need to set this below variable also in db class and make a connection to the constructor according to this.
$host = localhost;
$username = "";
$password ="";
$dbname = "";
$options = "";
Can anyone suggest how to set this variable in the DB class and how to call DB class from state.php page?
add this at the top of your state.php file
require 'db.php';
this if the db.php file in the same directory, if not then
require 'path_to_where_the_db.php_file_is/db.php';
I dont see the issue if you pass them on in the state.php but if you dont want to you can do this:
class db
{
public $isConnected;
protected $database;
private $_dbOptionArray;
const DB_USER = 'root';
const DB_PASS = 'pass';
const DB_HOST = 'host';
const DB_NAME = 'name';
public function __construct($username, $password, $host, $dbname, $options=array())
{
$this->_dbOptionArray = [];//set your options here
$this->isConnected = true;
try {
$this->database= new PDO("mysql:host={self::DB_HOST};dbname={self::DB_NAME};charset=utf8", self::DB_USER, self::DB_PASS, $this->_dbOptionArray);
$this->database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->database->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function select($query, $params=array()){
try{
$stmt = $this->database->prepare($query);
$stmt->execute($params);
return $stmt->fetch();
}catch(PDOException $e){
throw new Exception($e->getMessage());
}
}
}
Set parameters by creating a factory.
DatabaseFactory.php
include("db.php");
class DatabaseFactory
{
protected $db;
public function __construct()
{
$this->db = new db("root", "", "localhost", "bhaskar_hindi_dbs", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
public function getConnection()
{
return $this->db;
}
}
Then you can include DatabaseFactory.php in other pages without having to re-enter the parameters every time. Then use it like this:
include "DatabaseFactory.php";
$DBFactory = new DatabaseFactory();
$Database = $DBFactory->getConnection();
$query = ...; // your query
$Database->select($query);
You can easily change the parameters, reuse on all your pages or change database type this way later down the road if you wished.
You can use another function to extend parent function.
class dbConfig extends db {
private $engine;
private $host;
private $database;
private $user;
private $pass;
public function __construct(){
$this->engine = 'mysql';
$this->host = 'localhost';
$this->database = '';
$this->user = '';
$this->pass = '';
$dns = $this->engine.':dbname='.$this->database.";host=".$this->host;
parent::__construct( $dns, $this->user, $this->pass );
}
}

How to use the instance of DB class inside functions?

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

PHP Database Class Load Rows function (OOP)

I want to print out all content of the 'forum_question' table.
What am i doing wrong? No matter what, i will get the message "Nothing found!",
but i am sure the $db->connect DOES work, so it must be something with the query or loadRows functions.
This is my database class:
<?php
class Database {
private $host;
private $user;
private $password;
private $rows;
private $result;
private $dbName;
private $connection;
private $isReady;
public function __construct() {
$this->result = null;
$this->isReady = false;
}
/* setters */
public function setHost($host){ $this->host = $host; }
public function setUser($user){ $this->user = $user; }
public function setPassword($password){ $this->password = $password; }
public function setDbName($dbName){ $this->dbName = $dbName; }
/* Interface functions */
public function initiate($host=null,$user=null,$password=null,$dbName=null) {
if(isset($host,$user,$password,$dbName)==false) {
die("Please provide require settings.");
}
$this->setHost($host);
$this->setUser($user);
$this->setPassword($password);
$this->setDbName($dbName);
$this->isReady = true;
}
public function connect() {
if($this->isReady==false) {
die("Not ready to connect, please initiate connection");
}
$connection_string = "mysql:host=".$this->host.";dbname=".$this->dbName;
$this->connection = new PDO($connection_string, $this->user, $this->password);
$this->query("SET NAMES 'utf8'",$this->connection); // ensure character/language support
}
public function disconnect() {
$this->connection = null;
$this->isReady = false;
$this->setHost = null;
$this->setUser = null;
$this->setPassword = null;
$this->setDbName = null;
}
public function query($sql) {
$this->result = $this->connection->query($sql);
}
public function countRows() {
return $this->result->rowCount(); }
public function loadRows() {
if(!$this->result) die("Nothing found!");
$this->rows = array();
foreach ($this->result as $row) {
$this->rows[] = $row;
}
return $this->rows;
}
} // End of Database class
?>
This is my index file:
<?php
require_once 'class_database.php';
$db = new Database();
$db->initiate("localhost","USER","PASSWORD","DATABASE");
$db->connect();
$db->query("SELECT * FROM 'forum_question'");
$db->loadRows();
?>
Why don't you try with different connection script? For instance:
<?php
$mysql_server = "localhost";
$mysql_user = "USER";
$mysql_password = "PASSWORD";
$mysql_db = "DATABASE";
$mysqli = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($mysqli->connect_errno) {
printf("Connection failed: %s \n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
works fine, all you have to do is:
<?php
require_once "connection.php";
$query = "SELECT * FROM 'forum_question'";
$mysqli->query($query);
$mysqli->close();
Assuming that you saved the connection script in file "connection.php".

Categories