Using MySQLi in other classes [duplicate] - php

This question already has an answer here:
Using MySQLi from another class in PHP
(1 answer)
Closed 2 years ago.
I hope someone can help me with my small problem but I cannot figure it out. What I want to achieve is having one database.php file that connects to the database each time I call it. And then I want to be able to grab results, insert results etc in other files, but without having to have a seperate connect to the database line in those files.
What I have right now, is my database connection class:
<?php
$db_host = 'localhost';
$db_user = 'dbusername';
$db_pass = 'dbpassword';
$db_name = 'dbname';
class database {
public $mysqli;
public function connect($db_host, $db_user, $db_pass, $db_name)
{
$this->mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($this->mysqli->connect_errno)
{
return "An error occured while connecting to the database";
}
}
}
?>
Now when I include this file and setup a connection like so:
$whatever = new database();
I want to be able to perform some database actions with some functions in other classes like so:
require_once("whatever.class.php");
$test = new myclass();
$update = $test->updataDatabase();
And in my "whatever.class.php" file I have the following function:
public function grabResult($table, $where, $field)
{
$result = 'SELECT * FROM '.$table.' WHERE '.$where.' = '.$field;
$query = $this->mysqli->query($result);
And whatever I try, I always get the following error:
Call to a member function query() on a non-object in /home/etc/public_html/whatever.class.php on line 5
Basically what my question is, I want to be able to use "$this->mysqli" in another class without having to set up the database connection again in that class. I just want to include the database.class.php file and then connect plus being able to use $this->mysqli.
From another page I found this:
$newConnection = new database;
$newConnection->connect($db_host, $db_user, $db_pass, $db_name);
$mysqli = $newConnection->mysqli;
But that didn't do the trick. Same as the following, did not work:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
public function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
I have also tried extending the "myclass" from database, with no luck, I tried using "::parent", also without any luck. Any help is greatly appreciated since I been struggling with this for a few days now.

I think you have at least 3 ways to do this... (Maybe there are more ways)
databasde.php (with class) needs to be included first for following steps
1: The first one is to extend the dbclass to your class like
class myclass extends database {
public function myclass(){
parent::__construct();
//....
}
}
than you have all functions and vars in your myclass
2: The second way is
require_once(database.php);
class myclass {
private $db;
public function myclass(){ /* the constructor */
$this->db = new database();
}
public function grabResult($table, $where, $field)
{
$result = "SELECT * FROM {$table} WHERE {$where}={$field}";
return $db->mysqli->query($result);
}
}
3: The third way is
class myclass{
private $db;
public function myclass(){
$this->db = false;
}
public function setupDBHandler($dbHwNd){
$this->db = $dbHwNd;
}
public function grabResult($table, $where, $field)
{
if($this->db){
$result = "SELECT * FROM {$table} WHERE {$where}={$field}";
return $db->mysqli->query($result);
}
else{
return "Setup DBHandler first.";
}
}
}

Related

Using class database connection in other class

I have a class with a connection to a database
$db = new db();
class db {
public $server = 'localhost';
public $user = '';
public $passwd = '******';
public $db = '';
public $dbCon;
function __construct() {
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db);
}
function __destruct() {
mysqli_close($this->dbCon);
}
}
Now i want to make an other class and using the connection like this:
class Categories (
function GetCategory($cat) {
$myQuery = "SELECT * FROM test GROUP BY $cat";
$results = mysqli_query($this->dbCon, $myQuery);
return $results;
}
)
How can i use the connection in a other class?
Can somebody help me out whit this?
Make the $dbCon in your db class a static variable, so you can access it from category's using db::$dbcon as the connection variable. You could also make a static function returning the static dbcon variable, usefull tot check if it is actually a link and not null.
This is just one solution of many possibilities, but probably the easiest to implement because it isn't likely you need more connections to a db, so a static is perfect for it.
A static is nothing more then a variable living in the namespace it is defined in, you don't need to initialize the class in order to access it. It's value is shared across all instances of the object, so creating multiple DB class instances allows you tot just return a static if it was set in a previous DB class instance.
class db{
static $link;
static function connect(){
if(self::$link = mysqli_connect(....)){
return self::$link;
} else {
die('could not connect to db');
}
}
static function getcon(){
return isset(self::$link) ? self::$link : self::connect();
}
}
class Categories{
function GetCategory($cat){
$myQuery = "SELECT * FROM test GROUP BY $cat";
return mysqli_query(db::getcon(), $myQuery);
}
}
Create an object of the db class in the categories class. Then use that object to query the db accordingly. Also make sure you use a static variable in the db class. SO that the connection variable is created once and will be used all along the application.
Your db class may look like this
class db {
public $server = 'localhost';
public $user = '';
public $passwd = '******';
public $db = '';
public static $dbCon;
function __construct() {
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db);
}
function __destruct() {
mysqli_close($this->dbCon);
}
}
Your categories class may look like this
class Categories {
$connection=db::$dbCon;
if(!$connection){
$db=new db();
$connection=db::$dbCon;
}
function GetCategory($cat) {
$myQuery = "SELECT * FROM test GROUP BY $cat";
$results = mysqli_query($this->connection, $myQuery);
return $results;
}
}

PHP Database connection class issues

So, I'm in the middle of writing a web application for one of my clients, and I've decided to keep the database connection in a class. The following code is what I have:
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
}
I am using the standard PHP function of mysqli_query to send queries to the database. I am using the following to send queries to the database:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->$connection, 'QUERY');
}
I'm new to using classes in my code. I'm still learning, as we all are. I've checked about but cannot find a fix for my issue. I know what the issue is: it's an issue with the class being an object, and something to do with fetching the returned $connection variable from it.
How can I fix this issue so that I can connect correctly to my database? Also, could anyone point me in the direction of some documentation that I could learn the fix so I can tackle this in future.
Thank you!
There are a lot of different ways you could write a object to handle connections and queries to the database.
What matters most is what your trying to achieve.
I would think these would be a few features you would like to have.
Single Connection
Runs SQL and returns mysqli results.
Access to the connection for escaping values.
It looks like you want to store your credentials within the object it self. ( I would suggest passing these in as a value in __construct()
These are a few basic features, that could easily be expanded apon.
class databaseConnection {
//private $hostname = 'hn.app.dev';
//private $username = 'root';
//private $password = '';
//private $database = 'hn_app_dev';
private $connection; // this is where the object will store the connection for other methods to access it
public function __construct($host, $username, $password, $database)
//public function connect() {
$this->connection = mysqli_connect($host, $username, $password);
if ($host) {
$this->connection->select_db($database);
if (!$this->connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
// this is so databaseConnection $db can access the connection for escaping MySQLi SQL
public function connection(){
return $this->connection;
}
function fetch_from_db($query) {
//$connection = new databaseConnection(); // I don't believe you really want to create a instance of this object inside of itself
//$query = mysqli_query($connection->$connection, 'QUERY');
$query = $this->connection->query($query); // we will use the object oriented style instead of the above procedural line
return $query; // return the results to the $results var in the bottom example
}
// this is a magic function that is called when the object is destroyed, so we will close the connection to avoid to many connections
function __destruct(){
$this->connection()->close();
}
}
// make a new datbaseConnection class with specific credentials
$db = new databaseConnection('localhost', 'someuser', 'somepass', 'somedb');
$sql = 'SELECT * FROM tableName LIMIT 100';
// call the fetch_from_db function from the new databaseConnection $db
$results = $db->fetch_from_db($sql);
// print the results
while($result = $results->fetch_assoc()){
print_r($result); // print_r on each row selected from db
}
You can learn more about OOP and PHP Objects in the Manual and there are many tutorials available online about specifically classes to manage database connections and queries.
http://php.net/manual/en/language.oop5.php
Hope this helps!
If you're going to keep it in a class, you never call the connect() function. But if you want it connected when you initiate the class, change the connect() function to __construct() and remove the return and assign it to a public variable.
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public $connection;
public function __construct() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
$this->connection = $host;
}
}
}
After that, you can get the database connection in your function like:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->connection, 'QUERY');
}
Now, after having said all that, you don't want to create a new instance in every function to access the database. So possibly making it static and create an init() function of sorts so it takes less memory in the overall application.
For class documentation PHP's Classes/Objects page will help. Specifically the 'Examples' link.
<?php
class databaseConnection {
private $hostname = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'onlinylh_sggsfaculty';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password,$this->database);
if ($host) {
return $host;
}
else{
echo "Error";
}
}
}
function fetch_from_db($query) {
$conn = new databaseConnection();
$r = mysqli_query($conn->connect(), $query);
}
fetch_from_db()
?>
This Worked For me.

PHP Database Class query Fatal error

Folks,
Let me preface this by stating that I'm trying to learn OOP so rather than use one of the existing Mysqli abstraction layers out there, I wanted to write my own Class.
I have the class defined in a file, and I'm just trying to get a generic query working before I start writing specific query functions.
<?php
/* Database Config */
define('DB_NAME', 'project');
define('DB_USER', 'foo');
define('DB_PASS', 'bar');
define('DB_HOSTNAME', '127.0.0.1');
class Database {
private $host;
private $user;
private $pw;
private $db;
public $con;
public function __construct($hostname, $user, $pass, $db) {
$this->DB_HOSTNAME = $hostname;
$this->DB_USER = $user;
$this->DB_PASS = $pass;
$this->DB_NAME = $db;
}
public function connect() {
$this->con = new mysqli($this->hostname, $this->user, $this->pass, $this->db)
or die('Database unavailable');
$this->con->set_charset ('utf8');
}
public function query($sql) {
$stmt = $this->con->query($sql);
}
}
// Create a single global instance of the database class
global $DB;
$DB = new Database();
?>
Then I created a simple test.php containing:
<?php
include_once("include/config.inc");
if ($DB) {
$sql = "select user_login, user_name from users where 1 order by user_name, user_login";
$stmt = $DB->query($sql) or die($DB->errno.__LINE__);
$result = $stmt->fetch_array(MYSQLI_ASSOC);
var_dump($result);
}
else die('Database Unavailable');
?>
When I call that page I get
Fatal error: Call to a member function query() on a non-object in /www/htdocs/project/include/db.class.php on line 33
I'm not getting a die from the test page, so I believe it can reach the database, and I know the table holds data and the query works because if I switch to non Class based DB definition I get an array with expected data.
So I'm pretty sure it's a problem I created in the Class, I just can't figure out what it is. Advice please?
Seems your object wasn't created
this is your construct. It means when you create object you need to specify parameters
public function __construct($hostname, $user, $pass, $db)
Do it like this
$DB = new Database('hostname', 'dbuser', 'dbpass', 'db');
Your class is initialized fine, that's not the issue. The issue is that it can't find the query function on con, since you're not calling connect before you call query.
You should add a line inside your query function to call connect if con doesn't yet exist or isn't active, so you don't have to remember to call it before calling query.

Why does it say $con is an undefined variable when I defined it on line 2? [duplicate]

This question already has an answer here:
Using MySQLi from another class in PHP
(1 answer)
Closed 1 year ago.
I get a strange error.
This is my code:
<?php
$con=mysqli_connect("localhost","root","","testdatabase");
class database{
public function select($tableName){
$result = mysqli_query($con,"SELECT * FROM ".$tableName);
}
}
$database = new database();
?>
The error message is that $con is an undefined variable. But I define $con on line number 2?
When I var_dump con it also says NULL.
What am I doing wrong?
If you want to access to your $con var in a method or function, you have to globalize it inside your code :
public function select($tableName){
global $con;
$result = mysqli_query($con,"SELECT * FROM ".$tableName);
}
But you shouldn't do that, globals are evil !
This is how your code should be :
<?php
class database{
protected $con;
public function __construct($host, $user, $password, $dbname){
$this->con = mysqli_connect($host, $user, $password, $dbname);
}
public function select($tableName){
$result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database("localhost", "root", "", "testdatabase");
?>
The connection $con is available in the global scope. What you likely want to do is inject your mysql connection (in the form of mysqli object) in the constructor for your Database object. Here is a simple example:
<?php
$mysqli= new mysqli("localhost","root","","testdatabase");
class database{
protected $mysqli = null;
public function __contruct(MySQLI $mysqli = NULL) {
$this->mysqli = $mysqli;
}
public function select($tableName){
$result = $this->mysqli->query("SELECT * FROM ".$tableName);
}
}
$database = new database($mysqli);
?>
Note that since you are trying to go with an object-oriented paradigm, you might as well use mysqli in an object oriented fashion.
Add a construct function to your class and declare your connection inside this function.
class database{
private $con;
public function __construct(){
$this->con=mysqli_connect("localhost","root","","testdatabase");
}
public function select($tableName){
$result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database();

Start work with PHP OOP

I now learn PHP OOP and I want to get yours tips. I create DB connection class, is this okay?
How use "Database" class in another class? Always use "extends"?
Thanks
<?php
//Config
$db_user = 'root';
$db_pass = '';
$db_host = 'localhost';
$db_name = 'test';
class Database
{
private $Database;
private static $instance;
public static function instance()
{
if ( !self::$instance )
self::$instance = new Database();
return self::$instance;
}
public function connect($host, $user, $password, $name)
{
$this->db_link = mysql_connect($host, $user, $password);
mysql_set_charset('utf8');
mysql_select_db($name, $this->db_link);
}
public function query($query)
{
$sql = mysql_query($query);
$row = mysql_fetch_array($sql);
return $row;
}
}
class Book extends Database
{
public function getData2()
{
$sql = $this->query('SELECT * FROM users WHERE price = "7"');
return $sql['name'];
}
}
$db = Database::instance();
$db->connect($db_host, $db_user, $db_pass, $db_name);
$b = new Book();
$res = $b->getData2();
print_r($res);
?>
You can extends the database class but it is not what I suggest.
You could also use the keyword global inside the function where you actually need database to let the function get the database instance from outside; but still some people get nervous about global keyword.
You could pass the instance of the database class as argument of constructor of the class where you need database, in this way you will be able to call db methods with a simple chain: $this->db->connect();
As björn states, a book is not a database, wouldn't recommend extend.
One approach would be to on object initialization of book, pass the reference to the db-layer/object..
$myDb = new dbLayer($settings);
$myBook = new book($myDb);
$a = $myBook->getAllData($someParameter);
in the constructor of book you save the reference to the dblayer...
class book {
var $dbTier;
__constructor($db) {
$this->dbTier = $db;
...
regards,
//t
You can do something like this, this should be easy to understand
class User{
private $db;
public function __construct($db){
$this->db = $db;
}
}
The $db in the constructor parameter would be your database connection and required fom another file. All any how you get to it but not in the class.
require 'file from where you have your database';
$user = new User($db);
Anytime you like to user the database to make a query, you just reference it like below
$this->db->query();
You would not use extends here ideally unless Book is a subclass of Database. You would do something like:
class Book
{
var $db;
function __construct() {
$this->db = Database::instance();
}
}
Then the book class would use the instance of the database object and you can always access it with $this->db inside Book.

Categories