PHP MySQL Helper Functions for Single Results
March 21, 2007 • 1 min read
During many projects, I often need to retrieve just a single value or row from the database. Rather than setting up a WHILE
loop every time, I’ve created two simple helper functions that handle this perfectly.
The Functions
// Returns a single value from the first column
function mysql_one_data($query)
{
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
return $row[0];
}
// Returns a single row as an associative array
function mysql_one_array($query)
{
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
return $row;
}
Usage Examples
These functions make it incredibly simple to grab single pieces of data:
// Get a single value
$date = mysql_one_data("SELECT date FROM records WHERE id='2' LIMIT 1");
// Get a single row as an array
$user_info = mysql_one_array("SELECT firstname, lastname, date FROM records WHERE id='2' LIMIT 1");
// Use the array data
echo $user_info['firstname'] . ' ' . $user_info['lastname'] . ' (' . $user_info['date'] . ')';
These simple helper functions eliminate the need for repetitive code when you just need one result from your MySQL queries. Perfect for those quick data lookups that happen all the time in web development.