MySQL Return Single Data or Single Array with PHP
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\'].\')\';
comments powered by Disqus