Reusing a mysql connection in oop php [duplicate] - php

This question already has answers here:
Use global variables in a class
(4 answers)
Closed 7 years ago.
Solution taken from comment so I can't accept an answer for this to be closed. But I did post the actual solution that works for me below
I'm new to OOP and I just can't figure out, even after reading through quite few examples, how use the same mysql connection without using $GLOBALS.
If someone can explain it like I'm a two year old that would be super helpful.
This is my connection file.
$hostname = 'hostname';
$username = 'db';
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=db", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
but then to use this in a class or a function I do this:
class basic {
function simple($id) {
$query = $GLOBALS['dbh']->query("SELECT * FROM table WHERE id = $id");
$row = $query->fetch(PDO::FETCH_OBJ);
$thing = $row->partoftable;
echo $thing;
}
}
$first = new basic();
$first->simple(12);
This of course will return what I'm looking for the $thing with the id of 12. But how do I do this without the GLOBALS['dbh'] to connect to the db?
Also feel free to rip anything else apart but just keep in mind this was the easiest example of what I'm talking about.
Thanks in advance.
This is the solution that works for me based on the comment below.
class basic {
function __construct($dbh)
{
$this->dbh = $dbh;
}
function simple($id) {
$query = $this->dbh->query("SELECT * FROM table WHERE id = $id");
$row = $query->fetch(PDO::FETCH_OBJ);
$thing = $row->partoftable;
echo $thing;
}
}
$first = new basic($dbh);
$first->simple(12);
Thanks. hope this helps someone else.

class basic {
var $CONNECTION;
function __construct($dbh) {
$this->CONNECTION = $dbh;
}
function simple($id) {
$conn = $this->CONNECTION;
$query = $conn->prepare("SELECT * FROM table WHERE id = $id");
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
$thing = $row->partoftable;
echo $thing;
}
}
//class ends you can use thae class like this
$hostname = 'hostname';
$username = 'db';
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=db", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$first = new basic($dbh);
$first->simple(12);

You can create a class for database connection :
class MysqlDB
{
private $conn;
public function __construct($hostName, $userName, $passWord, $databaseName)
{
$this->conn = new PDO("mysql:host=$hostName;dbname=$databaseName", $userName, $passWord);
}
public function query($id)
{
//This is just a sample query
$this->conn->query("SELECT * FROM table WHERE id = $id");
return $query->fetch(PDO::FETCH_OBJ);
}
}
And then you can use in another class like:
class basic {
private $dbConn;
function __construct(){
$dbConn = new MysqlDB('hostName', 'username', 'password', 'database')
}
function simple($id) {
$row = $dbConn->query($id);
$thing = $row->partoftable;
echo $thing;
}
}
You can also create a database connection in common class and extend it with you class

I like this solution:
class db_connection
{
public static $sql_object = NULL;
public function __construct()
{
if ($sql_object === NULL)
{
// Initialize self::$sql_object
}
}
}
Then you can use it with:
$db = new db_connection();
// Do something with $db->sql_object
Since $sql_object is static, it will be initialized only once, no matter how many times you use new db_connection().

<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'db');
class DB_con {
function __construct()
{
$conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die('localhost connection problem'.mysql_error());
mysql_select_db(DB_NAME, $conn);
}
public function insert($fname,$lname,)
{
$res = mysql_query("INSERT users(first_name,last_name,) VALUES('$fname','$lname')");
return $res;
}
public function select($id)
{
$res=mysql_query("SELECT * FROM users WHERE id = $id");
return $res;
}
} ?>

Related

PHP: Using DB-connection inside of class

i'm updating from PHP5.6 to PHP7.0 and this doesn't work anymore:
$con=mysqli_connect(DATABASE_SERVER,DATABASE_USER,DATABASE_PASSWORD) or die(DATABASE_ERROR);
mysqli_select_db($con, DATABASE_NAME) or die(DATABASE_ERROR);
class DoSomeStuff()
{
function GetSomeDate()
{
$result=mysqli_query($con, "SELECT * FROM my_table");
}
}
Looks like the $con variable is not available inside the class.
Do i have to to something like this?
global $con=mysqli_connect()
Thanks!
The main pattern used is something like, pass database connection into constructor (dependency injection) and then store it in an instance variable ($this->con in this case). Then later database calls just use $this->con for the database connection...
$con=mysqli_connect(DATABASE_SERVER,DATABASE_USER,DATABASE_PASSWORD) or die(DATABASE_ERROR);
mysqli_select_db($con, DATABASE_NAME) or die(DATABASE_ERROR);
class DoSomeStuff
{
private $con;
// Create instance with connection
public function __construct( $con ) {
// Store connection in instance for later use
$this->con = $con;
}
public function doSomething() {
// Run query using stored database connection
$result=mysqli_query($this->con, "SELECT * FROM my_table");
}
}
// Create instance, passing in connection
$some = new DoSomeStuff ($con);
$some->doSomething();
heres something I've worked with recently
class Database {
private $_conn = null;
public function getConnection($password) {
if (!is_null($this->_conn)) {
return $this->_conn;
}
$this->_conn = false;
try {
$this->_conn = new PDO("mysql:host=localhost;dbname=databasename", 'root',
$password);
$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $this->_conn;
}
}
function conOpen() {
$servername = "localhost";
$username = "root";
$password = "password";
$db = new Database();
$conn = $db->getConnection($password);
return $conn;
}
Then use it like this
$con = conOpen();
You can check out PDO connection here

PHP PDO class use in different class (doesn't work)

I wanna get data on table and write a class. But this class doesn't work because pdo doesn't access. How can I get table data with this class?
$db = new PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx");
class uye extends PDO{
var $id;
var $kadi;
function cek($id){
$query = $db->query("SELECT * FROM btc WHERE id='{$id}'", PDO::FETCH_ASSOC);
if ( $query->rowCount() ) {
foreach( $query as $row ){
$this->id=$row["id"];
$this->kadi=$row["kadi"];
}
}
}
}
$bilgiler=new uye;
$bilgiler->cek(1);
echo $bilgiler->kadi;
So I'm running this off of fetching all data as I dont know where you're getting $id from.
I generally break my code up into files and folders as I found this easier to work with and others to work on.
// database connection file (dbc.php)
class Database
{
private $host = "127.0.0.1";
private $db = "";
private $user = "";
private $password = "";
public $conn;
public function dbConnect()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db, $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
I then make a common file, this is where you can store all of your frequently used functions or your static functions
// Common file (common.php)
require_once('dbc.php');
class DBCommon
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnect();
$this->conn = $db;
}
public function run($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
So to explain this a little more, you will see a function of run() this is just to save the tedious $this->conn->prepare on every query.. Now you can run $this->run()
The next would be your class file.. this is where your logic goes:
// your class file... (class.btc.php)
require_once "common.php";
class BTC extends DBCommon
{
public function getQuery()
{
$stmt = $this->run("SELECT * FROM `btc`");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$rows[] = $row;
}
return $rows;
}
}
Self explanatory..
And then your calling method.. Lets say index.php
// File you're calling your class from (index.php)
require_once "class.btc.php";
$fetch = new BTC();
$returnData = $fetch->getQuery();
foreach ($returnData as $data)
{
echo
"<p>$data->something</p>
<p>$data->somethingElse</p>";
}
It seems a little long winded I know, but the time you'll save overall will help!

Implementing mysqli procedural with a class

so recently I've been trying to use more procedural mysqli for practise, and have been looking at http://www.phpknowhow.com/mysql/mysqli-procedural-functions/, and also w3schools as reference, but i'm still having trouble so I thought I'd ask.
I have this database.php file where I have alot of stuff but the important stuff is
class Database{
public $host = DB_HOST;
public $username = DB_USER;
public $password = DB_PASS;
public $db_name = DB_NAME;
public $link;
public $error;
public function __construct(){
$this -> connect();
}
private function connect(){
$link = mysqli_connect($this->host,$this->username,$this->password,$this->db_name);
if(!$link){
echo "Failed".mysqli_error($link);
}
}
// create select method
public function select($query){
$result = mysqli_query($link,$query) or die("didnt work".mysqli_error($link));
if(mysqli_num_rows($result) > 0){
return $result;
}
else{
return false;
}
}
Now the way it currently works fine in my index.php file is simply by doing something like
$db = new Database();
//CREATe query
$query = "SELECT * FROM posts";
$posts = $db->select($query);
Is there any way to implement $posts = $db->select($query) with procedural functions? Before I have done stuff like mysqli_query($link,$query), but link is public here and inside a class so I can't do that, plus I want to access the function select . Thanks!
$link is not defined in your function select.
Modify your connect function:
private function connect() {
$this->link = mysqli_connect($this->host, $this->username, $this->password, $this->db_name);
if(!$this->link) {
echo "Failed: " . mysqli_error($this->link);
}
}
Now $this->link may be used in your select function:
public function select($query){
$result = mysqli_query($this->link, $query) or die("didn't work: " .mysqli_error($this->link));
if(mysqli_num_rows($result) > 0) {
return $result;
}
else{
return false;
}
}
I suggest you read the PHP OOP documenentation (at least the first chapters) to get a better understanding.

Using function to create a connection

I'm trying to create a connection using function in my other php file. So I can access it in every php file. How can I call the function inside my class from another php file. What is the proper way creating instance of my function will I put it in the top of my file or inside my class? I try to run my system but the connection won't load.
connection.php
<?php
DEFINE ('host', 'localhost');
DEFINE ('username', 'root');
DEFINE ('password', '');
DEFINE ('database', 'librarysystem');
function getConnection()
{
$myDB = mysqli_connect(host,username,password,database);
if (!$myDB)
{
trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error());
}
else
{
return $myDB;
}
}
?>
Another file where I'm gonna call my function or method.
loginCRUD.php
<?php
error_reporting(0);
require_once ('../connection/connection.php');
$myConnection = getConnection();
class loginCRUD
{
public function readLogin($dbusername,$dbpassword)
{
$statement = $myConnection->prepare("SELECT * FROM loginmodule WHERE loginUsername = ? AND loginPassword = ? LIMIT 1");
$statement->bind_param("ss", $dbusername, $dbpassword);
if($statement->execute())
{
$result = $statement->get_result();
if($result->num_rows)
{
$row = $result->fetch_assoc();
return $row;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
(new loginCRUD)->readLogin($dbusername,$dbpassword);
?>
There can be at least two possible ways of passing $myConnection to your loginCRUD class.
First is to create $myConnection in a class itself:
class loginCRUD
{
protected $dbCon;
public function __construct()
{
$this->dbCon = getConnection();
}
public function readLogin($dbusername,$dbpassword)
{
$statement = $this->dbCon->prepare("YOUR SQL")
// other codes
}
}
(new loginCRUD)->readLogin($dbusername,$dbpassword);
Second is to pass $myConnection as an argument to your class constructor:
class loginCRUD
{
protected $dbCon;
public function __construct($myCon)
{
$this->dbCon = $myCon;
}
public function readLogin($dbusername,$dbpassword)
{
$statement = $this->dbCon->prepare("YOUR SQL")
// other codes
}
}
$myConnection = getConnection();
(new loginCRUD($myConnection))->readLogin($dbusername,$dbpassword);
The reason you are getting an error is due to your variable scope. In your loginCRUDclass you try to access a variable called myConnection, it fails to find it because the scope of the function is only that function. It doesn't know that you mean the global declared variable. A correct way of fixing this should be:
...
public function readLogin($dbusername,$dbpassword)
{
global $myConnection;
$statement = $myConnection->prepare("SELECT * FROM loginmodule WHERE loginUsername = ? AND loginPassword = ? LIMIT 1");
$statement->bind_param("ss", $dbusername, $dbpassword);
if($statement->execute())
{
...
For reference: Accessing variables and methods outside of class definitions

PHP - PDO 'config' file equivalent

This may be a question that has been answered before - if so please just leave a comment below and I'll remove this one.
I have been learning classes in PHP and at the same time making the jump to PDO.
One concept I cant seem to find is how to acomplish the equivalent to this with classes:
config.php
<?php
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$con = mysql_connect($host, $user, $pass) or die("MySQL Error");
mysql_select_db("account_db", $con);
?>
another.php
<?php
require_once('config.php');
$selectStatement = "SELET foo FROM bar";
$selectQuery = mysql_query($selectStatement, $con);
?>
I haven't quite figured out how I would create a config file/class for a PDO connection and then use it in another class, i.e. Users as below:
<?php
class Users
{
private $_userId;
function setUserId($username)
{
// Use a predefined database handle to connect to a database to get the users ID - I assume using a preconfigured $dbh handle via an include or extend?
$sth = $dbh->prepare("SELECT id FROM users WHERE username = :username");
$sth->bindParam(':username', $username);
...
}
}
?>
Thanks all :)
In my projects, I prefer using a class with a static member which holds the PDO object.
<?php
class DB
{
private static $instance = null;
public static function get()
{
if(self::$instance == null)
{
try
{
self::$instance = new PDO('mysql:host=localhost;dbname=name', 'user', 'abc123');
}
catch(PDOException $e)
{
// Handle this properly
throw $e;
}
}
return self::$instance;
}
}
The I can access it like so:
<?php
require 'DB.php';
class Users
{
private $_userId;
function setUserId($username)
{
// Using DB::get() to get the PDO object
$sth = DB::get()->prepare("SELECT id FROM users WHERE username = :username");
$sth->bindParam(':username', $username);
...
}
}

Categories