PHP and Databases for the Lazy Sod
(Page 1 of 6 )
In this article Justin explains his ezSQL utility, which reduces code and development time for database operations in PHP. This is great for the lazy sod...and everyone else.Maybe it's just me, but after building database driven websites in PHP for the past six years I am starting to get more than a little tired of repeating myself. What I mean to say is...how many times, on how many different projects, and with how many different databases do I have to write something along the lines of:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password")
or
die("could not connect");
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result))
{
printf ("ID: %s Name: %s", $row[0], $row["name"]);
}
mysql_free_result($result);
?> Is there really any need to make my fingers type this kind of gunk so often? Surely there must be an easier way of working with databases than this, and if so, where do I find that kind of information?
You might say 'abstraction' and bring up names like PEAR and ADOdb, and you might be right (if the only thing important to you is being able to use the same code with different databases). The problem is you still have to type out lots of stuff whenever you want to deal with a database.
For example, here is the required code using ADOdb:
<?
include('adodb.inc.php');
$conn = &ADONewConnection('access');
$conn->PConnect('northwind');
$recordSet = &$conn->Execute('select * from products');
if (!$recordSet)
{
print $conn->ErrorMsg();
}
else
{
while (!$recordSet->EOF)
{
print $recordSet->fields[0].' '.$recordSet->fields[1].'
';
$recordSet->MoveNext();
}
}
$recordSet->Close();
$conn->Close();
?> Nothing wrong with that, you say. I agree. You can use the same code on lots of different databases, you say. Fair enough, but I want to be even lazier than that. Ah, you say.
Next: Atomic Operations >>
More MySQL Articles
More By Justin Vincent