Page 1 of 1

[SOLVED] connecting to a DB from inside a class

Posted: Sun Aug 21, 2005 8:30 pm
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

Posted: Sun Aug 21, 2005 8:34 pm
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.

Posted: Sun Aug 21, 2005 8:35 pm
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!!!");

Posted: Sun Aug 21, 2005 8:40 pm
by feyd
your instance of mysql may not like getting a database resource, try removing the second argument passed to mysql_query()

Posted: Sun Aug 21, 2005 8:52 pm
by HEMOglobina
Thank you very much feyd. That solved it :)