Issues connecting to a database using a class and mysqli

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
midnite
Forum Newbie
Posts: 14
Joined: Sun Nov 06, 2011 2:58 pm

Issues connecting to a database using a class and mysqli

Post by midnite »

Hi there guys,

I've just started the oop in php and i've managed to create a class and connect to the database using mysql_connect but i'm having some issues when i try to replace mysql_connect for mysqli_connect, can anyone point me in the right direction. Thanks fellas.

main_file.php

Code: Select all

<?php

require_once('file_includes/config.php');
require_once('file_includes/classes.php');
$db = new Connection(DB_HOST, DB_USER, DB_PASS, DB_NAME);

//inserção de um cliente
$result = $db->query('SELECT firstname FROM person');
	

$output .= '<ul>';

while ($row = mysqli_fetch_assoc($result)) {

	$query_result = htmlentities($row['firstname']);
	
	$output .= '<li>'.$query_result.'</li>';
}

$output .= '</ul>';
echo $output;

?>
classes.php

Code: Select all

<?php

class Connection 
{
	
	public function __construct($dbHost, $dbUser, $dbPass, $dbName)
	{
		
		//Prepare the variables
		$this->dbHost = $dbHost;
		$this->dbUser = $dbUser;
		$this->dbPass = $dbPass;
		$this->dbName = $dbName;
		
		//Call the connection
		$this->connect();
		
	}
	
	public function connect()
	{
		
		//Open the database connection
		$this->openConnection();
		
		//Select the database
		$this->selectDatabase();
		
	}
	
	public function openConnection()
	{
	
		//Create the connection
		$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die(mysql_error());	
		
	}
	
	public function selectDatabase()
	{
	
		//Select the database
		$this->selection = mysql_select_db($this->dbName) or die(mysql_error());
		
	}
	
	public function query($query)
	{
		
		//Run the query and return the result
		$this->result = mysql_query($query) or die(mysql_error());
		return $this->result;
		
	}	
	
	public function close()
	{
		return mysql_close();		
	}	
}
?>
and config:

config.php

Code: Select all

<?php

//Database connection details for the local website
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '******');

//Tutorial Database names
define('DB_NAME', 'phpmyadmin');


?>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Issues connecting to a database using a class and mysqli

Post by Celauran »

Don't reinvent the wheel.

Code: Select all

$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
Better still, take a look at PDO.
Post Reply