Database connection class

Hello. I am trying to create a database connection class.
For the connection I will have a filename config.inc.php. This will have all the parameters to pass to the new connection.
The next file is database_connection.php file. This file will have various variables and constructor for the connection. Also withing the database conneciton class, one the connection is etablished I would like to return the connection as a $link so I can use it in my queries in my php files.
Last I will have the database_query class in another file where I will have all the queries that will use the $link as the connection.
For some reasone I can get all the classed to work together. Any suggestions on how I could implement this. Thank you

CONFIG.INI.PHP

 <?php
 define('DB_SERVER', "localhost");
 define('DB_USER', "root");
 define('DB_PASS', "root");
 define('DB_DATABASE', "Users");
 ?>

DATABASE_CONNECTION.PHP

<?php
	class Database
	{

	var $host   = ""; //database server
	var $user     = ""; //database login name
	var $pass     = ""; //database login password
	var $database = ""; //database name

	public $link;

	public function Database($host, $user, $pass, $database)
	{
		$this->host=$host;
		$this->user=$user;
		$this->pass=$pass;
		$this->database=$database;
		
	}

	public function connect()
		{
			$this->link = new mysqli($this->host,$this->user,$this->pass,$this->database);
			if (mysqli_connect_error())
			{
				echo mysqli_connect_error();
				exit();
			}
			else
				return $this->link;

		}
	}
	?>

DATABASE.PHP

    <?php
    require "database_connection.php";
    require "config.inc.php";
    $conn = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
    $link = $conn->connect();
    ?>

What exactly isn’t working?

For example I have a function getData() in database.php file that worked when the database connection was within this file. the function selects all the data but uses $link which is the connection.

$stmt = $this->link->prepare("SELECT * FROM Users");

I guess it is not working because it can’t get the connection link.

So how do you know it isn’t working? Do you get any errors?

Creating a new instance of the database_query class where all my functions are, and calling a function, and it just doesn’t display anything. As I sayed, when this code was in my class where all the functions where, it all worked.

public $link;


public function connect()
{
	$link = new mysqli("localhost","root","root","Users");
	if (mysqli_connect_error())
	{
		echo mysqli_connect_error();
		exit();
	}
	else
		$this->link = $link;
}

Then I just use the link for all of my functions as shown above…

Can you show full code of that function?
I’m asking because code you showed above looks correct.
So I’m suspecting problem in other place.

Trying to access the function here and display it here.

<?php 


	
	require_once ('database.php');
	require "database_connection.php";
	require "config.inc.php";


	$me = new database_query();
	$array = $me->getData();

	echo "<table border= 1px><br>"; 
	echo "<tr>
			<th>ID</th>
			<th>Password</th>
			<th>First Name</th>  
			<th>Last Name</th>
		   </tr>";

	foreach ($array as $row) 
	{
	echo 
	"<tr>
		<td>" . $row['user_id'] . "</td>
		<td>" . $row['user_password'] . "</td>
		<td>" . $row['user_first_name'] .  "</td>
		<td>" . $row['user_last_name'] .  "</td>
	</tr>"; 
	}	
	echo "</table>";

	?>

The actual function in database.php where class is database_query

         <?php
            require "database_connection.php";
            require "config.inc.php";
           $conn = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
            $link = $conn->connect();


  class database_query
{

      public function getData()
    {

	$stmt = $this->link->prepare("SELECT * FROM Users");
	$stmt->bind_param();
	if ($stmt->execute())
	{
		$result = $stmt->get_result();
		while($row = $result->fetch_array(MYSQLI_ASSOC))
			{ 
			$row = array_map('stripslashes', $row);
			$dataArray[] = $row;
			}
	} 
	return $dataArray;		
     }
}
  ?>

I can’t see how the database connection in the $link variable is getting in to the database_query object, yet the getData() method refers to it as $this->link on its first line.

Ok, now i see.
You have two classes:

class Database
class database_query

You store a link in object of Database class, but trying to access it in object of database_query class. That is wrong, because in database_query there is no $this->link (cuz you made that link in another class, not that one).

So you should pass your link from Database to database query, for example:

require "config.inc.php";
require "database_connection.php";    
require_once ('database.php');

$conn = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$link = $conn->connect();
$query = new database_query($link); // -- passing $link here to constructor
$array = $query->getData();

and in database.php leave only class definition with new constructor:

class database_query { 

    private $link; // here you'll store link from Database

    public function __construct($link){
        $this->link = $link;
    }

    public function getData(){
            // now $this->link is available here
            // and contains correct link
    }

}
2 Likes

__construct($link) perhaps? :wink:

1 Like

Sure, i fixed my post, thanks
Have been working with ActionScript last week :smile:

Maybe doing something like the following would be easier?

<?php
class Database {

  private $_connection;
  // Store the single instance.
  private static $_instance;

  // Get an instance of the Database.
  // @return Database: 
  public static function getInstance() {
    if (!self::$_instance) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }

  // Constructor - Build the mysqli Connection:
  public function __construct() {
     $this->_connection =new mysqli($this->host,$this->user,$this->pass,$this->database);
		if ($this->_connection->connect_error) {
				die('Connect Error (' . $this->_connection->connect_errno . ') '	. $this->_connection->connect_error);
		}		 
  }

  // Empty clone magic method to prevent duplication:
  private function __clone() {
    
  }

  // Get the PDO connection:    
  public function getConnection() {
    return $this->_connection;
  }

}
/* How to use the Database Class */
$connect = Database::getInstance(); // Get the Database Instance:
$myCon = $connect->getConnection(); // Setup the Database Connection:

The suggestion for a singleton instance in a database connection class is a reasonable one, but that’s a rather buggy implementation I’m afraid. Sorry! (die() function in the constructor, __construct declared as public, no static init method to get the connection params in there in the first place).

Using a dependency injection container would be better than using a singleton but I think that would just be muddying the waters at this stage. Maybe it would be better if the OP gets some working code first and then learns how to progress?

I have this where I am trying to call the function.

		<?php 
	require "config.inc.php";
	require "database_connection.php";    
	require_once ('database.php');


	$conn = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
	$link = $conn->connect();
	$query = new database_query($link); // -- passing $link here to constructor
	$array = $query->getData();

	echo "<table border= 1px><br>"; 
	echo "<tr>
			<th>ID</th>
			<th>Password</th>
			<th>First Name</th>  
			<th>Last Name</th>
		   </tr>";

	foreach ($array as $row) 
	{
	echo 
	"<tr>
		<td>" . $row['user_id'] . "</td>
		<td>" . $row['user_password'] . "</td>
		<td>" . $row['user_first_name'] .  "</td>
		<td>" . $row['user_last_name'] .  "</td>
	</tr>"; 
	}	
	echo "</table>";


	?>

DATABASE.PHP

Here is my function.

<?php

	class database_query{

	private $link;

                public function __construct($link)
		{
		$this->link = $link;
		}
                    
                public function getData()
		{

			$stmt = $this->link->prepare("SELECT * FROM Users");
			$stmt->bind_param();
			if ($stmt->execute())
			{
	    		$result = $stmt->get_result();
	    		while($row = $result->fetch_array(MYSQLI_ASSOC))
	    			{ 
	    			$row = array_map('stripslashes', $row);
					$dataArray[] = $row;
	    			}
			} 
			return $dataArray;		
		}
               }

And this is where the connection is made:
DATABASE_CONNECTION.PHP

<?php
		class Database
		{

		var $host   = ""; //database server
		var $user     = ""; //database login name
		var $pass     = ""; //database login password
		var $database = ""; //database name
		public $link;

		public function Database($host, $user, $pass, $database)
		{
			$this->host=$host;
			$this->user=$user;
			$this->pass=$pass;
			$this->database=$database;
			
		}

		public function connect()
			{
				$this->link = new mysqli($this->host,$this->user,$this->pass,$this->database);
				if (mysqli_connect_error())
				{
					echo mysqli_connect_error();
					exit();
				}
				else
					return $this->link;

			}
		}

		?>

STILL WON’T WORK/…

Ok. I did sort it out somehow… It does work. Now I need to fix something else, for some reason can’t log in. Thanks anyway for the help.

All sorted out in the end. :slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.