I was recently introduced to the idea of classes in PHP, and after some research I've come to the conclusion that I need to store database related functions in a class to access later. It has worked for the most part, but some use cases I am still confused with. For example,
Below is an example of how I would normally connect to my database and display information from user id's in a table
dbcon.php:
<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");
require_once("functions.php");
?>
functions.php
function getUserInfo($id) {
$query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
Some random file:
require_once("dbcon.php");
$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
$userinfo = getUserInfo($row['userid']);
echo $userinfo['name'];
}
?>
I don't feel like this method of querying the database and displaying information is the neatest or most efficient way possible. I read this article about using classes to tamper with a database and call functions that I created in the class.
My first question is this: When I try to access $con in functions.php, it is undefined. How can I pass the variable from dbcon.php to functions.php over the require_once function?
I also would like to know what the best way to store my connection to the database is, and if there are any tutorials on how to set that up.
I hope you understood that lol.
You can do it like this way:-
Dbconnection.php:-
<?php
Class DbConnection{
function getdbconnect(){
$conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
return $conn;
}
}
?>
Function.php:-
<?php
require_once('Dbconnection.php');
Class WorkingExamples{
function getUserInfo($id) {
$Dbobj = new DbConnection();
$query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
}
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>
Note:- this is an example, try it by changing values according to your requirement and get the result.
<?php
class DatabaseConnection
{
private $host = "127.0.0.1";
private $dbname = "online_english";
private $dbUsername = "root";
private $dbPass = "";
private $charset = 'utf8mb4';
private $dsn;
public function tryConnect(){
try{
$this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
$DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
$DBH->exec("set names utf8");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch (PDOException $e){
$e->getMessage();
}
}
}
?>
<?php
class Database{
const DB_HOSTNAME = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = 'root';
const DB_NAME = 'stockganesha';
public $_db_connect;
protected $_sql;
protected $_result;
protected $_row;
function db_connect(){
$this->_db_connect = mysqli_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD,self::DB_NAME) or die(mysql_error());
return $this->_db_connect;
}
function sql(){
$this->_sql = 'SELECT * FROM customers';
}
function query(){
$this->_result = mysqli_query($this->_db_connect,$this->_sql);
}
function fetch_array(){
while($this->_row = mysqli_fetch_array($this->_result)){
$username = $this->_row['first_name'];
echo "<ul>";
echo "<li>".$username."</li>";
echo "</ul>";
}
}
function db_close(){
mysqli_close($this->_db_connect);
}
}
and Import this in another class
<?php
require_once('../Config/Dbconnection.php');
include './model.php';
class CustomerDTO{
private $mysql;
function __construct() {
$database = new Database();
$this->mysql = $database->db_connect();
}
function create($customer){
$firstName = $customer->getFirstName();
$lastName = $customer->getLastName();
$emailId = $customer->getEmailId();
$mobileNumber = $customer->getMobileNumber();
$dateOfBirth = $customer->getDateOfBirth();
$phoneNumber = $customer->getPhoneNumber();
$termAndCondtion = $customer->getTermAndCondition();
$result = mysqli_query($this->mysql, "Insert into customers (first_name,last_name,email_id,mobile_number,date_of_birth,phone_number,term_and_condition)
values('$firstName','$lastName','$emailId','$mobileNumber','$dateOfBirth','$phoneNumber','$termAndCondtion')");
return $result;
}
function read(){
$result = mysqli_query( $this->mysql, "Select * from customers");
return $result;
}
function update($id, $customer){
$result = mysqli_query($this->mysql, "update customers set
first_name = ".$customer->getFirstName()."
last_name = ".$customer->getLastName()."
email_id = ".$customer->getEmailId()."
mobile_number = ".$customer->getMobileNumber()."
date_of_birth = ".$customer->getDateOfBirth()."
phone_number = ".$customer->getPhoneNumber()."
term_and_condition = ".$customer->getTermAndCondition()."
where id = ".$customer->getId());
return $result;
}
public function delete($id){
$result = mysqli_query($this->mysql, "delete from customers where id =".$id);
return $result;
}
}
Related
I wrote a class for PDO and need to disconnect PDO => ( I don't know how to do it )
I don't know code wrote is structurally correct?!
use $this->returnconn(); for db connection
Please guide me...
Sample code:
class conn {
public $inner;
public function returnconn() {
$CONF = $TMPL = array();
// The MySQL credentials
$CONF['host'] = 'localhost';
$CONF['user'] = 'root';
$CONF['pass'] = '';
$CONF['name'] = 'cmss';
$dsn ="mysql:host=".$CONF['host'].";dbname=".$CONF['name']."";
try{
$conn = new PDO($dsn,$CONF['user'],$CONF['pass']);
$conn ->exec("SET CHARACTER SET UTF8");
}catch(PDOException $e){
die($e->getMessage());
}
return $conn;
}
public function select(){
switch ($this->inner->switch){
case "select":
$sql="SELECT ".$this->inner->todo." FROM ".$this->inner->table." WHERE ".$this->inner->sql."";
$result=$this->returnconn()->prepare($sql);
/*
* this->returnconn();
*/
$result->execute();
if($result->rowCount()<=0){
return '{"msg":"empty "}';
}else{
return $result->fetch(PDO::FETCH_ASSOC);
}
break;
}
}
}
/* receive data */
$obj = new conn;
$iner = array();
$iner['table'] = 'category';
$iner['switch'] ='select';
$iner['todo'] = '*';
$iner['sql'] = '`id` IS NOT NULL ORDER BY `id` ASC';
$in = json_decode(json_encode($iner));
$obj ->inner = $in;
echo json_encode($obj ->select());
Do need a function to disconnect?
I have 3 files: dbconnect (here's declaration of $pdo), core.php (file with class to manage) and test.php.
I want to receive data from DB, but I have error:
Notice: Undefined variable: pdo in C:\xampp\htdocs\project\core.php on line 24
In dbconnect $pdo is in try catch, but before this I put: $pdo=null(to make variable accessible) but it doesn't work.
dbconnect ---> core.php(error here) ---> test.php;
//dbconnect.php
<?php
$mysql_host = 'localhost';
$username = 'root';
$password = '';
$database = 'db';
$pdo = null;
try {
$pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
?>
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
?>
Anyone can solve this? Thanks.
This is a scoping problem. $pdo doesn't exists in your getCore class.
You can make a DatabaseConnect class to manage your db access.
You can use this basic class for your database connection :
<?php
class DatabaseConnect {
private $mysql_host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'db';
private $pdo = null;
public function getPdo(){
return $this->pdo;
}
public function __construct(){
try {
$this->pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
}
}
?>
You can getting your PDO instance in an other class with calling DatabaseConnect object -> getPdo() :
- Instannciate a new DatabaseConnect.
- Get PDO instance with the methof of the class.
Like that :
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect->getPdo();
You next code :
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect-getPdo();
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
You need to pass $pdo to the getLinks() function as an input to make it available for use. you could try getLinks($pdo)
Good morning.
I'm trying to make a DB class to connect and retrieve results from my DB. So, I think with the class is everything good. But, the results won't appear.
Here is my DB class:
<?php class Conexao {
var $host = "localhost";
var $usuario = "root";
var $senha = "xxxxxx";
var $banco = 'restaurante';
private $mysqli;
public function Abrir()
{
$this->mysqli = new mysqli($this->host, $this->usuario, $this->senha, $this->banco);
}
public function Fechar()
{
$this->mysqli->close();
}
}
class Comando {
public function Executar($sql)
{
$con = new Conexao();
$con->Abrir();
$re = $con->mysqli->query($sql);
$con->Fechar();
return $re;
}
}
?>
And here is where I'm trying to retrieve the results:
<?php
$queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
if ($queryMesasAtivas->num_rows > 0) {
while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) {
echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>";
}
}
else {
echo '<option>Nenhuma mesa ativa</option>';
}
?>
I tried some modifications but, nothing changes. Everytime it's still not working. What's wrong?
As the Comando::Executar is not static, but rather declared as public function..., you will have to do something such as:
$comando = new Comando();
$queryMesasAtivas = $comando->Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
if ($queryMesasAtivas->num_rows > 0) {
while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) {
echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>";
}
}
else {
echo '<option>Nenhuma mesa ativa</option>';
}
Or declare the method as static, namely:
public static function Executar($sql)
{
$con = new Conexao();
$con->Abrir();
$re = $con->mysqli->query($sql);
$con->Fechar();
return $re;
}
And then you can use the double colon (::) syntax:
$queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
I would suggest not calling an open and close every time you run a query, but rather a class like this:
class Conexao
{
private $link;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
$this->link = mysqli_init();
$this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
}
This is then used as such:
$conexao = new Conexao("host", "username", "password", "db_name");
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
This is not only smaller, but more lightweight on the server because you aren't permanently opening and closing database connections, reducing CPU use and memory use.
Using static properties for the host etc. (keeps them in memory even after __destruct is used so you do not need to redeclare them every time):
class Conexao
{
private $link;
private static $host, $username, $password, $dbName;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
static::$host = $host ? $host : static::$host;
static::$username = $username ? $username : static::$username;
static::$password = $password ? $password : sattic::$password;
static::$dbName = $dbName : $dbName : static::$dbName;
$this->link = mysqli_init();
$this->link->real_connect(static::$host, static::$username, static::$password, static::$dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
}
$conexao = new Conexao("host", "username", "password", "db_name");
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
$conexao->__destruct(); // Destroy the class
$conexao = new Conexao(); // Reinitialise it
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
Using a config instance of the connection class:
config.php file:
<?php
require_once 'path/to/Conexao.php';
$conexao = new Conexao("host", "username", "password", "db_name");
?>
index.php file:
<?php
require_once 'config.php';
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
?>
The class now has a parent on my github!
I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?
ERROR is : Fatal error: Call to undefined function Connect_DB() in
C:\wamp\www\movie\movies.php on line 12
config.php :
<?php
//error_reporting(0);
class Connection{
private $host = "localhost";
private $username = "root";
private $password = "";
private $db = "movies";
private $connect;
private $q;
function Conn(){
$this->connect = #mysql_connect($this->host, $this->username, $this->password);
return $this->connect;
}
function Select(){
mysql_unbuffered_query('SET NAMES utf8');
return mysql_select_db($this->db);
}
function Query($sql){
$this->q = mysql_query($sql);
return $this->q;
}
function Rows(){
return mysql_num_rows($this->q);
}
function Object(){
return mysql_fetch_object($this->q);
}
}
?>
movies.php:
<?php
class Movies{
function Connect_DB(){
$data = new Connection;
if(!($data->Conn())) header("Location: 404.php");
if(!($data->Select())) header("Location: 404.php");
return $data;
}
function getImdb(){
$q = "SELECT * FROM top250";
$data = Connect_DB();
$ch = $data->Query($q);
if($ch){
$i=0;
while($r = $data->Object()){
$result["name"][$i] = $r->name;
$result["genre"][$i] = $r->genre;
$result["imdb"][$i] = $r->imdb;
$result["year"][$i] = $r->year;
$result["releaseDate"][$i] = $r->releaseDate;
$result["country"][$i] = $r->country;
$result["imgPath"][$i] = $r->imgPath;
$i++;
}//while
return $q;
}else{
$result = false;
return $result;
}//else
}//getImdb
}
?>
Here is html file:
<?php
require "config.php";
require "movies.php";
$imdb = new Movies;
$result = $imdb->getImdb();
?>
<!DOCTYPE HTML>
<html>
<head>
.....
I couldn't find where error is ? I have 2 class (config.php and movies.php) Config.php has mysql connection settings and movies has getting a table from mysql and html file include 2 file and show table. Can someone help me ?
you are not calling CONNECT_DB correctly. In a class when you want to call another method we use $this->method(). So change the line $data = Connect_DB(); to $data = $this->Connect_DB();