21 Mar, 2007
MySQL Return Single Data or Single Array with PHP
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.
Similar Posts:
- Fade In and Out Images from a Single Directory Using jQuery (with plugin)
- Compare Two MySQL Tables
- Display Last.fm’s Recent Tracks on Web Site with PHP Function
- Turn 2D Array into a HTML Dropdown with PHP
- MySQL Full-Text Stopwords Array


October 16th, 2008 @ 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.
July 4th, 2011 @ 12:56 am
I couldn’t get the mysql_one_data function to work. Is this a built in function or a function that isn’t supported anymore? I like the idea of using this instead of having to use an array for one piece of data. It seems like a waste that way.
July 6th, 2011 @ 4:51 pm
You need to have the mysql_one_data function declared before you call it. I usually store it in another file and just require that file when I know I’m going to use those two functions.
July 6th, 2011 @ 4:52 pm
I would steer away from using COUNT(*). Try counting one field instead if possible – such as COUNT(id)