Jump to content

OOP Database Issues


xbase

Recommended Posts

Here is my db class:

 

$conn = new database_conn();
$dbh = $conn->db;

 

here is my class to create the top nav:

class top_nav
{
var $i;
var $l;

function build() 
	{
		global $hostname;
		global $dbh;

		$l = chr($this->i); 	

	$valid = $dbh->getOne("SELECT * FROM md_models WHERE alias REGEXP '^($l)'"); 

	// Print valid letters
	if ($valid!=0)
	{
			$letter = '<td  width=20 align=center>
			<a href="index.php?cmd=find&l='.$l.'" 
			style="color: black; text-decoration: none; font-weight: bold">'.$l.'</a>
			</td>';
	 }
	 else
		{
			$letter = '<td  width=20 align=center style="color: #CCCCCC; font-weight: bold">'.$l.'</td>';
		}

	return $letter;

}
}

 

how come this is not working and I get an invalid object for $valid = $dbh->getOne.

 

I use PHP 4.4.3 (not my choice). Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/38668-oop-database-issues/
Share on other sites

Every time someone uses global variables in a class God kills a puppy.

 

Pass object instances to your class through the constructor.

 

$conn = new database_conn();
$dbh = $conn->db;

$nav = new top_nav($dbh);

 

class top_nav
{
var $i;
var $l;
        var $dbh;

function top_nav($dbh)
        {
           $this->dbh = $dbh;
        }

function build() 
	{

		$l = chr($this->i); 	

	$valid = $this->dbh->getOne("SELECT * FROM md_models WHERE alias REGEXP '^($l)'"); 

	// Print valid letters
	if ($valid!=0)
	{
			$letter = '<td  width=20 align=center>
			<a href="index.php?cmd=find&l='.$l.'" 
			style="color: black; text-decoration: none; font-weight: bold">'.$l.'</a>
			</td>';
	 }
	 else
		{
			$letter = '<td  width=20 align=center style="color: #CCCCCC; font-weight: bold">'.$l.'</td>';
		}

	return $letter;

}
}

 

Best,

 

Patrick

Link to comment
https://forums.phpfreaks.com/topic/38668-oop-database-issues/#findComment-185967
Share on other sites

i just asked about this. i stored the instance of the class in a session var so that i only have to initialize it once

 

$_SESSION['var'] = new class();

 

the thing i discovered is that if you do it this way, you need to include the class file before you do session_start();

 

then if you want to use a method anywhere in your scripts, just do

 

$_SESSION['var']->method();

Link to comment
https://forums.phpfreaks.com/topic/38668-oop-database-issues/#findComment-186000
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.