473,769 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OOP - Problems with adapting some code

113 New Member
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_MysqlStateme nt 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.p hp):
[php]
<?php
/*
* A simple contact book class
* @package
* @author chromis
*/
class ContactBook {
protected $dbh;
protected $dbtable;
protected $name;

public function __construct($db h, $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("Cont actBook: Database resource invalid.");
}
$query = "INSERT INTO " . $this->dbtable . " (name,email,add ress)
VALUES (
'" . mysql_escape_st ring($contact->getName()) . "',
'" . mysql_escape_st ring($contact->getEmail()) . "',
'" . mysql_escape_st ring($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>Cont acts:</h2>\n");

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

// Fetch row results from query
$stmt = $this->dbh->execute($query );
//$ret = $this->dbh->fetch_row();
}
public function show_entry($ent ry_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($us er, $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("Cann ot connect to database.");
}
if(!mysql_selec t_db($this->dbname, $this->dbh)) {
throw new Exception("Cann ot select database.");;
}
}
public function execute($query) {
if(!$this->dbh) {
$this->connect();
}
$ret = mysql_query($qu ery, $this->dbh);
if(!$ret) {
throw new Exception;
}
else if(!is_resource ($ret)) {
return TRUE;
}
else {
$stmt = new DB_MysqlStateme nt($this->dbh, $query);
$stmt->result = $ret;
return $stmt;
}
}
public function prepare($query) {
if(!$this->dbh) {
$this->connect();
}
return new DB_MysqlStateme nt($this->dbh,$query);
}
}
class DB_MysqlStateme nt {
protected $result;
protected $dbh;
public $query;
public $binds;

public function __construct($db h, $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("Quer y not executed");
}
return mysql_fetch_row ($this-result);
}
public function fetch_assoc() {
return mysql_fetch_ass oc($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_escap e_string($pv)." '",$query);
}
$this->result = mysql_query($qu ery, $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.ph p");

// 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($db h, "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>Cont acts:</h2>\n");

$query = "SELECT name,email,addr ess 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 2450
r035198x
13,262 MVP
Remove the $ on $this->$dbhost to $this->dbhost
Jul 31 '08 #2
chromis
113 New Member
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
1218
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 figured out a way to structure my program, but I'm wondering whether my solution is good Python programming practice. Most of my program lives in a class. My plan is to have a superclass that performs the generic functions and subclasses to define...
17
2660
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 for the sidebar navigation, The second cell is the main content and the third (in the second row) for the page footer. I cannot figure out why on some pages a gap opens up on the side of image at the top of the navigational side bar. It appears...
14
2326
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 going to use .Net......I highly recommend signing up for the free KBAlertz newsletter at http://www.kbalertz.com/default.aspx. Looking at all of the errors and quirks sometimes makes me wonder if this thing is really ready for prime time.
12
2262
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: http://www.celticbear.com/weblog/ looks fine in Firefox and Opera, but in IE6, the main body block positions itself below the left menu bar. I've W3C validated the XML Schema, HTML, and CSS and fixed a couple of errors and all three now give me a "valid"...
16
2219
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 has been working flawlessly for about 2 years. I am now at a point where these databases need to be converted to Access 2003. I think I read somewhere on this forum that the newer versions of Access are not as tolerant to multiple users...
3
1269
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 usercontrol, asp.net simply ignores the styles. This include only has a div element, that serves as the footer of my pages. If I define the styles inside the main page, the div is correctly displayed.
4
1391
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 checked - totalised the number of checked boxes in each column The system works fine until you have more than 10 rows, at which point the myrow substr(1,1) fails to correctly identify the row number
4
2006
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 href="../basicstyle.css" rel="stylesheet" type="text/css"> <style type="text/css"> <!-- .style1 {color: #CCCC99} --> </style>
15
7729
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 code would either select the next value in the member list or the single value. The original post can be found here. This is the code gits helped me write: for (var i = 0; i < attribList.id.length; i++) { var attrib = {};
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10050
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8876
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3570
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.