Mar
21
Posted by john in mysql, php, programing
Quite a few times during projects I only want to find a single value from the database. But rather than setting up WHILE loop, I’ve been using a quick function that does two things perfectly.
Here’s the function:
// returns single result
function mysql_one_data($query)
{
$one=mysql_query($query);
$r=mysql_fetch_row($one);
return($r[0]);
}
// returns single array
function mysql_one_array($query)
{
$one=mysql_query($query) or die (mysql_error());
$r=mysql_fetch_array($one);
return($r);
}
Say for example I wanted just the date of a record. All I have to do is make sure to call the function and then do the following:
// single value
$date = mysql_one_data("SELECT date FROM records WHERE id='2' LIMIT 1");
// single array
$date_info = mysql_one_array("SELECT firstname, lastname, date FROM records WHERE id='2' LIMIT 1");
// you can then use the single $date_info array like
echo $date_info['firstname'].' '.$date_info['lastname'].' ('.$date_info['date'].')';
Just let me know if you have any questions about this.







October 16th, 2008 at 12:56 pm
Good stuff. I like it.
Sometimes, I just need to grab a quick COUNT(*), and I can see how this would come in handy. Or would you happen to know of any other time-and-resource-saving tips that would allow me to grab the actual COUNT(*) value quickly?
At any rate, I love this. Thank you.
[Reply]