lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: MySQL query routine
I've been using MySQL queries in PHP for quite a while now, but it still feels messy and like I'm doing it for the first time every time I have to add one to my code. I have a partner now who's taking over most the database management, but I still have to use them now and again. So I finally sat down and put together a little template:

// OPEN DB
open_db(DB_NAME);

// DB : get TIMESTAMP of last MOD REPORT

# SQL query
$SQL['select'] = <<<SQL1
SELECT `ID`, `timestamp`
FROM $table
ORDER BY `timestamp` DESC
SQL1;

# run query
$_sqlr = mysql_query($SQL['select']) or trigger_error('MySQL error number '.mysql_errno().': '.mysql_error(), E_USER_WARNING);

# fetch results
if ( mysql_num_rows($_sqlr) > 0 )
{
while ( $_ROW = mysql_fetch_assoc($_sqlr) )
{
$RESULT[] = $_ROW;
}
}
else
{
trigger_error('no records found', E_USER_NOTICE);
}

# free results
if ( is_resource($_sqlr) )
{
mysql_free_result($_sqlr);
}


Here's a skeleton of the routine:

// PHP-MySQL routine

# open DB

# SQL query

# run query

# fetch results

# free results


Thus far, it's helped immensely. I'll post my open_db() function when I have a chance.