linein designs

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:

1 Comment »

Comment by WebGyver

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.

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post



Please Support Our Friends

Send emails with ease on this SMTP server by JangoSmtp.com.

Banner

About

My name is John Veldboom and have been in design and web programing for just over 8 years now. Started off as a hobby in high school but it has developed into a full time job now. I always tell people that if I wasn't doing this at work each day, I would be at home doing it for free. I love it!

Please visit the contact page to drop me a message.