/    Sign up×
Community /Pin to ProfileBookmark

OO, classes, and PHP4

Seeing as I learn faster by doing than just reading, I decided to start playing around with classes in PHP. I’m running PHP4 (as that is what my web host supports), and decided I’d start by re-inventing the wheel and create a class for interfacing with MySQL.

Question 1: As far as I can tell, PHP4 classes are upward-compatible to PHP5, with the caveat that E_STRICT warnings will be generated by attribute declarations since PHP4 does not support the public/private/protected visibility declaration. Is there any other “gotcha” when running a PHP4 class under PHP5 I should be aware of?

Question 2: Below is the current incarnation of my DB class definition. It works as intended, I’m just curious if any OO experts see anything glaringly wrong in its design with regard to good OO practices.

[code=php]
<?php
######################################################################
# CLASS: DB
# PURPOSE: Provide common database functionalities
# METHODS:
# DB: (constructor) initiate connection to MySQL and select database
# querySelect: process a SELECT query and return results in array
# queryOther: process queries which are not SELECTs (e.g.: INSERT,
# DELETE, UPDATE)
#
# HISTORY:
# Created: 2005/12/04 by Charles Reace
######################################################################
class DB {

### ATTRIBUTES ###

# modify dataFile to specify CSV file that defines rest of fields:
var $connectData = array(‘dataFile’ => ‘c:db.txt’,
‘host’ => ”,
‘user’ => ”,
‘password’ => ”,
‘database’ => ”);

var $connection = “”; # db connection handle from mysql_connect()

### METHODS ###

######################################################################
# bool DB()
# constructor
#
# Establishes connection with MySQL and selects database as per
# parameters in $this->connectData, which has most fields populated
# from CSV file $this->connectData[‘dataFile’]
######################################################################
function DB()
{
$handle = @fopen($this->connectData[‘dataFile’], ‘r’);
if($handle === FALSE)
{
die(“Unable to open dataFile.”);
}
while( ($line = fgetcsv($handle, 1000)) !== FALSE )
{
if(count($line) == 2)
{
$this->connectData[$line[0]] = $line[1];
}
}
fclose($handle);
foreach($this->connectData as $value)
{
if(empty($value))
{
die(“Not all connection data fields populated”);
}
}
$this->connection = @mysql_connect($this->connectData[‘host’],
$this->connectData[‘user’],
$this->connectData[‘password’]);
if(!$this->connection)
{
die(“Unable to connect to database server”);
}
$result = mysql_select_db($this->connectData[‘database’]);
if(!$result)
{
die(“Unable to select database – ” . mysql_error());
}
return(TRUE);
} # end constructor method

######################################################################
# array querySelect(str queryString [, bool debug])
#
# PURPOSE: process a SELECT query
# RETURNS: array of query results as array[rowNbr][fieldname],
# FALSE if query failed, or 0 if now rows returned
######################################################################
function querySelect($queryString, $debug = FALSE)
{
$result = @mysql_query($queryString, $this->connection);
if(!$result) # query failed
{
if($debug) # die only if debug on
{
die(“querySelect(): Query failed – $queryString – ” . mysql_error());
}
return(FALSE); # false = mysql error
}
if(mysql_num_rows($result) == 0) # query OK, but now rows returned
{
return(0); # 0 = no rows found that satisfied query
}
$count = 0;
# if we got here, we got query results, so put them in array:
while($row = mysql_fetch_assoc($result))
{
foreach($row as $key => $value)
{
$output[$count][$key] = $value;
}
$count++;
}
return($output);
} # end method querySelect()

######################################################################
# int queryOther(str queryString [, bool debug])
#
# PURPOSE: process a query other than a SELECT
# RETURNS: num of rows affected, or FALSE if failed
######################################################################
function queryOther($queryString, $debug = FALSE)
{
$result = @mysql_query($queryString, $this->connection);
if(!$result) # query failed
{
if($debug) # die only if debug on
{
die(“querySelect(): Query failed – $queryString – ” . mysql_error());
}
return(FALSE); # false = mysql error
}
# query OK, return affected rows
return(mysql_affected_rows($this->connection));
} # end method queryOther()

} # end class DB
?>
[/code]

Well, if you’ve read this far, my sincerest thanks!
?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@chazzyDec 04.2005 — I have no compatibility information to give you.

as far as your class goes.

1) You don't need to return anything in a constructor.

2) I'm pretty sure, in PHP, you don't need to define the var $connectData and var $connection. Those should be defined as part of your constructor, but depends on your taste.

[B]Edit:[/B] nevermind, those are needed.

3) My outlook on OOP may be a little different. I might do something more along these lines:
[code=php]
class DB {
var $user;
var $password;
var $db;
var $server;
var $connection;
function DB(){
$this->user='user';
$this->password='password';
$this->db='database';
$this->server='server';
$this->connection=mysql_connect($this->server,$this->user,$this->password) or die('Unable to connect to mysql server: '.mysql_error());
$this->connection=mysql_select_db($this->db) or die ('Unable to change database: '.mysql_error());
}
}[/code]

which i'm not even sure is proper syntax, mind you.

but either way, I don't think it's the best idea to keep both the file contents and the connection info in the same array.
Copy linkTweet thisAlerts:
@ShrineDesignsDec 04.2005 — i have notice that constructors do not return the return value, example[code=php]<?php
class foo
{
function foo()
{
return false;
}
}
$foo = new foo;
var_dump($foo); // outputs the object
var_dump(foo::foo()); // should output false
?>[/code]
thus, if the return value is critical within the script you should be able to do this[code=php]<?php
// foo class ...

if(!foo::foo())
{
die('class foo failed as expected');
}
// create instance
$foo = new foo;
// ...
?>[/code]
of cource, this is by no means very practical for database usage, as it would create an extra un-needed connection (if the connection is made within the constructor), if not handled correctly

by the way, nice job nogdog

EDIT: just thought of something[code=php]<?php
class foo
{
function foo(&$retval)
{
$retval = 1;
}
}
$bool = 0;
$foo = new foo($bool);

if(!$bool)
{
die('class foo failed');
}
// ...
?>[/code]
Copy linkTweet thisAlerts:
@NogDogauthorDec 05.2005 — Thanks for the feedback, guys - some good food for thought.
Copy linkTweet thisAlerts:
@SpectreReturnsDec 05.2005 — Constructors and deconstructors can not return values, as constructors are not actually run (just initiated), and thus have nowhere to put the values. PHP5 is backwards compatable, so PHP4 OOP will work on it. Besides the fact that there are no deconstructors in PHP4, there is basically no difference.
×

Success!

Help @NogDog spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 7.21,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ,
analytics: Fullres
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: @Nanditha,
tipped: article
amount: 1000 SATS,
)...