#native_company# #native_desc#
#native_cta#

Best Practices: Database Abstraction Page 3

By Allan Kent
on January 15, 2001

Let’s take another look at those two scripts side by side:
Native PHP Functions PEAR

<?php

include( 'dbinfo.php' );

// no need to include PEAR

$conn mysql_connect$dbhost$dbuser$dbpass );

mysql_select_db($dbname);

$sql 'SELECT * FROM demo';

$demoResult mysql_query$sql );

while ( 
$demoRow mysql_fetch_row$demoResult ) ) {

    echo 
$demoRow[2] . '<br>';

}

mysql_close ($conn);

?>



<?php

include('dbinfo.php');

require_once( 
'DB.php' );

$db DB::connect"mysql://$dbuser:$dbpass@$dbhost/$dbname" );

// no need to select DB

$sql 'SELECT * FROM demo';

$demoResult $db->query($sql);

while (
$demoRow $demoResult->fetchRow()) {

    echo 
$demoRow[2] . '<br>';

}

$db->disconnect();

?>



Great. So we’ve found another way of grabbing stuff data from my MySQL database. You may ask what the point is. Why not just do it the normal way ? Indulge me here for a moment.
Suppose you decided to migrate to PostgreSQL.
connect - yourusernamehere
CREATE TABLE "demo" (
	"demo_id" int8 DEFAULT nextval('serial'::text) NOT NULL,
	"demo_stamp" int8,
	"demo_text" character varying(50),
	PRIMARY KEY ("demo_id")
);
COPY "demo" FROM stdin;
1	978872113	Record number 1
2	978872652	Record number 2
3	978872652	Record number 3
4	978872652	Record number 4
5	978872652	Record number 5
.
There’s the same database dump but from PostegreSQL. Now if you had used native PHP database functions in your code you would first have to work out how the pgsql functions worked, and then you’d need to go play search and replace through all of your code.
Course if you had used PEAR, you would go and change the line
$db = DB::connect( “mysql://$dbuser:$dbpass@$dbhost/$dbname” );
to
$db = DB::connect( “pgsql://$dbuser:$dbpass@$dbhost/$dbname” );
I did, reran the script and this is what I got:
Record number 1
Record number 2
Record number 3
Record number 4
Record number 5
Fairly nifty.