Need some PHP help (connecting and retrieving db)

Jake

Paragon
Joined
Nov 14, 2010
Messages
2,264
Reaction score
2
FP$
246
Hey guys.

I coded this up a bit ago, but it's not working.

I realize I could do this simpler, but I'm trying to use OOP (I don't want to be thought of as a n00b for not using it, which I am a noob, but I don't want to show it :b)

So here is the code..


Index:
Code:
<?php
	include('db.class.php');

	$con = new config('localhost','root','');
	$etc = new database($con);
	$etc->openCon();
	mysql_select_db('tester') or die(mysql_error());
	$query1 = mysql_query('SELECT * FROM person') or die(mysql_error());
	$rows = mysql_fetch_array($query1) or die(mysql_error());
		echo 'First: ' . $rows['First'];
		echo 'Age:'    . $rows['Age'];
	$etc->closeCon();
?>

Here's db.class.php:
Code:
<?php
<?php

class config {

	public $host;
	public $user;
	public $pass;

	function __construct($host=NULL,$user=NULL,$pass=NULL) {

		$this->host = $host;
		$this->user = $user;
		$this->pass = $pass;

	}

	function __destruct() {}

}

class database {

	private $host;
	private $user;
	private $pass;
	private $config;

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

	function __destruct() {}

	public function openCon() {
		mysql_connect($this->host,$this->user,$this->pass);
		if (mysql_errno()) {
			printf('Failed to connect: %s', mysql_error());
		} else {
			echo 'Connected to DB successfully.<br/><br/>';
		}
	}

	public function closeCon() {
		try {
			mysql_close();
			echo 'Successfully closed connection.<br/><br/>';
		} catch (exception $e) {
			echo $e;
		}
	}
}

?>

I'm sure there are blaring errors in this. Could anyone help me find and fix them?

It says: Access denied for user ''@'localhost' to database 'tester'

Not sure why.

I specified root as the user, but it came back with '' as the user I requested to use.

it got the host and the database right.

There is no password to my local root user, so...

Any ideas?
 
In the constructor of Database class, you are passing a config object and saving it to a private variable and never set values for $host, $user and $pass in Database class.

So in mysql_connect, you should use $this->config->host instead of $this->host and so on.
Code:
mysql_connect($this->config->host,$this->config->user,$this->config->pass);
 
In my database constructor I just added:

Code:
		$this->user = $this->config->user;
		$this->pass = $this->config->pass;
		$this->host = $this->config->host;

To set the variables, then I set the mysql_connect call equal to a variable to satisfy the db selector function. All is good!

🙂
 
Back
Top Bottom