[SOLVED] connecting to a DB from inside a class

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
HEMOglobina
Forum Newbie
Posts: 6
Joined: Tue Aug 09, 2005 7:23 pm

[SOLVED] connecting to a DB from inside a class

Post by HEMOglobina »

I'm using PHP 4 here and although I have used classes many times, I'm not being able to do it correctly regarding DB conectivity.
Here is the simplified code of my class:

Code: Select all

<?php
class App {
	var $db = null;
	
	function App() {
			$this->db = $this->conectDB();	
	}
	function conectDB() {
		$dbname     = 'myDB'; 
		$dbserver   = 'localhost'; 
		$dbuser     = 'root';
		$dbpass     = 'password';
		$db = mysql_connect($dbserver, $dbuser, $dbpass) or trigger_error(mysql_error(),E_USER_ERROR);
		mysql_select_db($dbname, $db);
		return $db;
	}
	function executeQry() {		
		$query = "SELECT * FROM sampletable";
		$result = mysql_query($query,$this->db);
		if (!$result) {
			echo "query did not get executed";
		}
	}
}
?>
Everytime I call the executeQry (after instantiating the class, of course), the echo gets executed, which means that the query was invalid.
How structure a class with database conectivity? Unfortunatly PEAR:DB is not an option.
Any help is greatly appreciated,
HEMOglobina
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

I dont think there is anything wrong with your code. I have one more similar to yours.
if it echoes, then you should have supplied improper query format or such a table or field in the query do not exist.
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

$db = mysql_connect($dbserver, $dbuser, $dbpass) or trigger_error(mysql_error(),E_USER_ERROR);
I found out..it should be

Code: Select all

$this->db = mysql_connect($dbserver, $dbuser, $dbpass) or trigger_error(mysql_error(),E_USER_ERROR);
if you had given an die or trigger_error statement here then you might have identified earlier.

Code: Select all

result = mysql_query($query,$this->db) or die("unable to execute query!!!");
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

your instance of mysql may not like getting a database resource, try removing the second argument passed to mysql_query()
HEMOglobina
Forum Newbie
Posts: 6
Joined: Tue Aug 09, 2005 7:23 pm

Post by HEMOglobina »

Thank you very much feyd. That solved it :)
Post Reply