Using function to create a connection - php

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

Related

Call to undefined method in php

Here is my config.php
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'xxxx');
define('DB_USER', 'xxxx');
define('DB_PASS', 'xxxx');
?>
And It is DB.php
<?php
include 'config.php';
class DB {
public static $pdo;
public static function connection(){
if (!isset(self::$pdo)) {
try {
self::$pdo = new PDO('mysql:host='.DB_HOST.'; dbname ='.DB_NAME,DB_USER, DB_PASS);
}catch(PDOException $e){
echo $e->getMessage();
}
}
return self::$pdo;
}
public static function prepareOwn($sql){
return self::connection()->prepare($sql);
}
}
?>
3rd file is Student.php
<?php
include 'DB.php';
class Student {
public $table = 'student_info';
public function readAll(){
$sql = "SELECT * FROM $this->table";
$stmt = DB::prepareOwn($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
?>
But When I try to access readAll() from index.php using spl_autoload_register() Then I can see Fatal error: Call to undefined method DB::prepareOwn()
Can anyone help me to solve the problem??
Many thanks.
Sahidul
i copied your code into mine and saw your error. but as i guessed, first you will get an error with this line inside db.php:
return self::$pdo->prepare($sql);
Fatal error: Call to a member function prepare() on null
where prepare function came from? $pdo is just a static property in this class and it doesn't have a function called prepare! fix this line
Updated
the problem is you forgot to call connection method inside your prepareOwn. so your new prepareOwn function should be:
public static function prepareOwn($sql) {
self::connection();
return self::$pdo->prepare($sql);
}
i hope this code will work for you
class MySQLDatabase {
// Class attributes
private $host_name = "localhost";
private $database_name = "XXXXXXX";
private $database_username = "XXXXXXX";
private $database_password = "XXXXXXX";
private $is_connected;
private $connection;
private $statement ;
// construct
public function __construct() {
$this->open_connection();
}// End of construct
// connection method
public function open_connection() {
try {
$this->is_connected = TRUE ;
// PDO Connection
$this->connection = new PDO("mysql:host=".$this->host_name.";dbname=".$this->database_name.";charset=utf8",$this->database_username,$this->database_password);
// Error reporting
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,FALSE);
} catch(PDOException $errors) {
$this->is_connected = FALSE ;
self::catch_errors($errors);
}
}// End of open connection method
// Get connection method
public function connection(){
return $this->connection ;
}
// Close connection method
public function close_connection() {
$this->connection = null;
}// End of close connection method
private static function catch_errors($errors) {
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
// query method
public function query($sql){
return $this->statement = $this->connection->prepare($sql);
}
}// End of database class
$database = new MySQLDatabase();
class Student {
protected static $table = 'My_table';
public function readAll(){
global $database;
try{
$sql = "SELECT * FROM ". self::$table;
$stmt = $database->query($sql);
$stmt->execute();
return $stmt;
}catch(PDOException $error){
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
}
}
$c = new Student();
$s = $c->readAll();
$stmt = $s->fetchAll(PDO::FETCH_ASSOC);
foreach($s as $v){
var_dump($v);
}

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!

Reusing a mysql connection in oop php [duplicate]

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

Select PHP PDO best way to make

I have a question on how to draw a connection to a select box that is inside a function.
I call this way:
Function MySQL:
mysql.php
function conectar() {
try {
$dbh = new PDO("mysql:host=localhost;dbname=adm-new", 'root', '');
} catch (PDOException $dbe) {
echo $dbe->getMessage();
}
return $dbh;
}
$conn = conectar();
Function select:
menu.php
function z_menu_todos() {
global $conn;
$z_menu = "SELECT *
FROM z_menu
ORDER BY posicao ASC";
return $conn->prepare($z_menu);
}
I did not want to call the variable global $conn.
What would be the best way to do?
I would create a DatabaseFactory class which would serve for creating database connection, like this:
ConnectionFactory.php
class ConnectionFactory {
private $_connection;
public function __construct($dbName, $dbUser, $dbPassword, $dbHost = 'localhost'){
try {
$this->_connection = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPassword);
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
throw new DatabaseFactoryException('Could not create connection:' . $e->getMessage());
}
}
public function getConnection(){
return $this->_connection;
}
}
After that I would create MenuRepository class which would server for executing queries associated with Menu, like this:
MenuRepository.php
class MenuRepository {
private $_connection;
public function __construct(PDO $connection){
$this->_connection = $connection;
}
public function getMenus(){
$stmt = $this->_connection->prepare("SELECT * FROM z_menu ORDER BY posicao ASC");
$stmt->execute();
return $stmt->fetchAll();
}
}
I would create configuration in separate file, like this:
config.php
define('DB_NAME', 'adm-new');
define('DB_USER', 'root');
define('DB_PASS', '');
After that I would use:
index.php
require __DIR__ . '/config.php';
require __DIR__ . '/ConnectionFactory.php';
require __DIR__ . '/MenuRepository.php';
$connectionFactory = new ConnectionFactory(DB_NAME, DB_USER, DB_PASS);
$connection = $connectionFactory->getConnection();
$menuRepository = new MenuRepository($connection);
$menus = $menuRepository->getMenus();
class Database
{
protected $conn;
public function __construct()
{
try {
$this->conn = new PDO("mysql:host=localhost;dbname=adm-new", 'root', '');
} catch (PDOException $dbe) {
echo $this->conn->getMessage();
}
}
public function z_menu_todos()
{
$z_menu = "SELECT *
FROM z_menu
ORDER BY posicao ASC";
return $this->conn->prepare($z_menu);
}
}
Usage
$database = new Database();
$stmt = $database->z_menu_todos();
Modify this as you require, this is a very basic example of how to do this, do not just copy and paste it.
In this case, you should avoid using global variables, because you can easily pass the connection to method as method argument, like this:
function conectar() {
try {
$dbh = new PDO("mysql:host=localhost;dbname=adm-new", 'root', '');
} catch (PDOException $dbe) {
echo $dbe->getMessage();
}
return $dbh;
}
$conn = conectar();
function z_menu_todos($conn) {
$z_menu = "SELECT * FROM z_menu ORDER BY posicao ASC";
return $conn->prepare($z_menu);
}
However, it might be a good idea to create a separate class for managing your database connection and other stuff purely related to database and another class for executing SQL queries against your menu table.

Any simpler / better way of making a mysql singleton db class in php?

Here's the one I'm using:
<?php
final class Database {
private static $oDb;
public static function init() {
if(self::$oDb == NULL)
{
self::$oDb = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die(mysql_error());
mysql_select_db('mysql_db_name', self::$oDb) or die (mysql_error());;
}
return self::$oDb;
}
public function query($sql)
{
return mysql_query($sql) or die(mysql_error());
}
}
?>
Usage:
$oDb = Database::init();
$sql = foo;
$oDb->query($sql);
Assuming that I only want it to connect and execute this one query function, are there any improvements I should make on the class? Memory or efficiency of code?
Also, is there an efficient way I can get the db credentials from a config file? I know I can't use includes inside my class.
I usually use lazy initialization for this sort of situation and only have one public method (in this case), with a private constructor to prevent outside instantiation (per the Singleton pattern):
class Database {
private static $instance;
private $conn;
private function Database() {
// do init stuff
require_once('dbconfig.php'); // contains define('DB_USER', 'webuser'); etc...
$this->conn = mysql_connect(DB_HOST, DB_USER, DB_PASS); // do error checking
}
public static function getInstance() {
if(!self::$instance) {
self::$instance = new Database();
}
return self::$instance;
}
public static function query($sql) {
$instance = self::getInstance();
return mysql_query($sql, $instance->conn);
}
}
Then you can just call $dbHandle = Database::getInstance() anytime you need to use it. Or in this case since a static query method is defined, you can use Database::query("select * from xx;"); without having to call any sort of init at all.
That's a simple as it gets, that will work fine.
You can pass your credentials to init();
include(config.php);
$oDb = Database::init( DB_HOST, DB_NAME, DB_USER, DB_PASSWORD );
$sql = foo;
$oDb->query($sql);
You can use an include inside a function inside a class
<?php
final class Database {
private static $oDb;
public static function init() {
if(self::$oDb == NULL)
{
include('config.php')
self::$oDb = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME, self::$oDb) or die (mysql_error());;
}
return self::$oDb;
}
public function query($sql)
{
return mysql_query($sql) or die(mysql_error());
}
}
?>
or you can just pass the variables...
<?php
final class Database {
private static $oDb;
public static function init($host, $user, $pass, $name) {
if(self::$oDb == NULL)
{
self::$oDb = mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($name, self::$oDb) or die (mysql_error());;
}
return self::$oDb;
}
public function query($sql)
{
return mysql_query($sql) or die(mysql_error());
}
}
?>
or you can store the credentials in a php.ini file
<?php
final class Database {
private static $oDb;
public static function init($db_name) {
if(self::$oDb == NULL)
{
self::$oDb = mysql_connect() or die(mysql_error());
mysql_select_db($db_name, self::$oDb) or die (mysql_error());;
}
return self::$oDb;
}
public function query($sql)
{
return mysql_query($sql) or die(mysql_error());
}
}
?>
php.ini file:
mysql.default_host="host"
mysql.default_user="user"
mysql.default_password="password"
For singleton classes, the model that Dan Breen followed is cleanest and very common. However, in this case, I would also allow the getInstance method to accept some parameters so that you can override your default configuration at instantiation time, or just get a reference without creating a connection (both use-cases happen from time to time).
Database.php
require_once("../path/to/config/database.php");
class Database {
private static $instances = array();
private function Database($host, $user, $password, $name) {
// do init stuff
}
public static getInstance(
$host=DB_HOST, $user=DB_USER, $password=DB_PASSWORD, $name=DB_NAME
) {
$key = strtolower($host . $user . $password . $name);
if ( !$self::instances[$key] ) {
$self::instances[$key] = new Database($host, $user, $password, $name);
}
return $self::instances[$key];
}
}
..config/database.php:
define("DB_HOST", "localhost");
define("DB_USER", "mrsqlguy");
define("DB_PASS", "!!!");
define("DB_NAME", "just_another_wordpress");
Edit: I've changed it to act more like a flyweight to ensure that you only get one instance for each connect location/database. This addresses your concerns and maintains a degree of flexibility.

Categories