473,288 Members | 2,350 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,288 software developers and data experts.

OOP - Problems with adapting some code

113 100+
Hi there,

I've been reading an OOP book recently and it gives some nice Adaptor / Template patttern code to wrap around the php Mysql functions. I thought that I'd try and create a Simple Address book using similar methods, but I'm having some trouble with using the class functions (I'm new to OOP in PHP 5).

So far I've written a Contact Book class and a Contact class. The Contact Book class has add, edit, delete and display functions for manipulating and displaying data in a database. My intention is to use the DB_Mysql, DB_MysqlStatement and DB_Mysql_Prod classes which I lifted from the book for the database interactions.

The following are my ContactBook and Contact classes (contacts.inc.php):
[php]
<?php
/*
* A simple contact book class
* @package
* @author chromis
*/
class ContactBook {
protected $dbh;
protected $dbtable;
protected $name;

public function __construct($dbh, $dbtable, $name) {
$this->dbh = $dbh;
$this->dbtable = $dbtable;
$this->name = $name;
$this->display();
}
public function add($contact) {
if(!is_resource($this->dbh)) {
throw new Exception("ContactBook: Database resource invalid.");
}
$query = "INSERT INTO " . $this->dbtable . " (name,email,address)
VALUES (
'" . mysql_escape_string($contact->getName()) . "',
'" . mysql_escape_string($contact->getEmail()) . "',
'" . mysql_escape_string($contact->getAddress()) . "'
);";
$stmt = $this->dbh->execute($query);
}
public function edit($contact) {
}
public function delete($contact) {
}
public function display() {
print("<h1>" . $this->name . " Contact Book</h1>\n");
print("<h2>Contacts:</h2>\n");

$query = "SELECT name,email,address FROM " . $this->dbtable;

// Fetch row results from query
$stmt = $this->dbh->execute($query);
//$ret = $this->dbh->fetch_row();
}
public function show_entry($entry_id) {
$query = "SELECT * FROM $dbtable WHERE entry_id = :1";
$stmt = $this->dbh->prepare($query)->execute($entry_id);
}
}
class Contact {
protected $name;
protected $email;
protected $address;

public function __construct() {
$this->name = $name;
$this->email = $email;
$this->address = $address;
}
public function getName() {
return $this->name;
}
public function getEmail() {
return $this->email;
}
public function getAddress() {
return $this->address;
}
}
?>[/php]

The classes lifted from the book (db.inc.php):

[php]
<?php
/*
* MySQL Database Handling Classes
*
* @package DB_Mysql
* @author chromis
*/
class DB_Mysql {
protected $user;
protected $pass;
protected $dbhost;
protected $dbname;
protected $dbh; // Database connection handle

public function __construct($user, $pass, $dbhost, $dbname) {
$this->user = $user;
$this->pass = $pass;
$this->dbhost = $dbhost;
$this->dbname = $dbname;
$this->connect();
}
public function connect() {
$this->dbh = mysql_connect($this->$dbhost, $this->$user, $this->$pass);
if(!is_resource($this->dbh)) {
throw new Exception("Cannot connect to database.");
}
if(!mysql_select_db($this->dbname, $this->dbh)) {
throw new Exception("Cannot select database.");;
}
}
public function execute($query) {
if(!$this->dbh) {
$this->connect();
}
$ret = mysql_query($query, $this->dbh);
if(!$ret) {
throw new Exception;
}
else if(!is_resource($ret)) {
return TRUE;
}
else {
$stmt = new DB_MysqlStatement($this->dbh, $query);
$stmt->result = $ret;
return $stmt;
}
}
public function prepare($query) {
if(!$this->dbh) {
$this->connect();
}
return new DB_MysqlStatement($this->dbh,$query);
}
}
class DB_MysqlStatement {
protected $result;
protected $dbh;
public $query;
public $binds;

public function __construct($dbh, $query) {
$this->query = $query;
$this->dbh = $dbh;
if(!is_resource($dbh)) {
throw new Exception("Not a valid database connection");
}
}
public function fetch_row() {
if(!$this->result) {
throw new Exception("Query not executed");
}
return mysql_fetch_row($this-result);
}
public function fetch_assoc() {
return mysql_fetch_assoc($this-result);
}
public function fetchall_assoc() {
$retval = array();
while($row = $this->fetch_assoc()) {
$retval[] = $row;
}
return $retval;
}
public function execute() {
$binds = func_get_args();
foreach($binds as $index => $name) {
$this->binds[$index + 1] = $name;
}
$cnt = count($binds);
$query = $this->query;
foreach($this->binds as $ph => $pv) {
$query = str_replace(":$ph", "'".mysql_escape_string($pv)."'",$query);
}
$this->result = mysql_query($query, $this->dbh);
if(!$this->result) {
throw new MysqlException;
}
return $this;
}
}
/*
* Test class - an example of the Template pattern.
* Hides the database specific connection parameters in the previous classes.
*
*/
class DB_Mysql_Prod extends DB_Mysql {
protected $user = "***";
protected $pass = "***";
protected $dbhost = "***";
protected $dbname = "***";

public function __construct() {}
}
?>
[/php]

And the code to initialise them (index.php):

[php]
include("inc/db.inc.php");
include("inc/contacts.inc.php");

// Create new mysql db connection
$dbh = new DB_Mysql_Prod();

// Create contact book passing in db connection, db table and name of contact book
$myContactBook = new ContactBook($dbh, "simple_address_book", "E-Simple");

[/php]

The function that I'm working on at the moment is the display function in the ContactBook class, what I'm trying to do is write a function correctly which retrieves the contacts from the database using the db classes and then displays them, first of all though i need to get the query statement to work:

[php]
public function display() {
print("<h1>" . $this->name . " Contact Book</h1>\n");
print("<h2>Contacts:</h2>\n");

$query = "SELECT name,email,address FROM " . $this->dbtable;

// Fetch row results from query
$stmt = $this->dbh->execute($query); (query statement)
//$ret = $this->dbh->fetch_row();
}
[/php]

I'm getting the following error though:

Expand|Select|Wrap|Line Numbers
  1. Notice: Undefined variable: dbhost in D:\sites\eddy\php\simple-address-book\inc\db.inc.php on line 23
  2.  
  3. Fatal error: Cannot access empty property in D:\sites\eddy\php\simple-address-book\inc\db.inc.php on line 23
I can't work out why dbhost is not defined, I must be implementing the classes incorrectly, anyone any ideas?

Thanks,

chromis
Jul 31 '08 #1
2 2429
r035198x
13,262 8TB
Remove the $ on $this->$dbhost to $this->dbhost
Jul 31 '08 #2
chromis
113 100+
Heheh it was staring me in the face! Thanks!
Jul 31 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Jeffrey Barish | last post by:
I have a small program that I would like to run on multiple platforms (at least linux and windows). My program calls helper programs that are different depending on the platform. I think I...
17
by: FDYocum | last post by:
I am having problems with a Web site that I've designed and I am grinding my teeth in frustration. The pages are built around a table with four cells. The first cell is spanned two rows and is...
14
by: Jim Hubbard | last post by:
Are you up to speed on the difficulties in using the 1.1 .Net framework? Not if you are unaware of the 1,596 issues listed at KBAlertz (http://www.kbalertz.com/technology_3.aspx). If you are...
12
by: news | last post by:
I'm having a heck of a time, and I'm hoping someone can take a quick look and see if they can recognize what might be the problem and point me the right direction. My blog page:...
16
by: Wayne Aprato | last post by:
I have several Access 97 databases which are split into front end and back end running off a server. The front end mde is shared by 2 or 3 - absolute maximum of 6 concurrent users. This scenario...
3
by: Chris Leffer | last post by:
Hi. I am having some problems to adapt a stylesheet for an asp.net page. When I use this .css file on a classic asp page through an include all works ok, but if I change the include to an...
4
by: timothy.pollard | last post by:
Hi all A few weeks ago a nice man called Evertjan helped me create a form validation system that took a table of four columns of checkboxes and: - allowed only one checkbox in each row to be...
4
NoPeasHear
by: NoPeasHear | last post by:
My problem - the first cell of my table is adapting the .nav class rather than .menu class that I am assigning it. How can I fix it? My code starts out as the following... <link...
15
RMWChaos
by: RMWChaos | last post by:
As usual, an overly-long, overly-explanatory post. Better too much info than too little, right? A couple weeks ago, I asked for some assistance iterating through a JSON property list so that my...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.