note 108765 modified in function.mysql-fetch-array by danbrown
| From: | danbrown@php.net | Date: | Wed, 23 May 2012 18:10:26 +0000 |
| Subject: | note 108765 modified in function.mysql-fetch-array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188174@lists.php.net to get a copy of this message | ||
Just thought I'd share these helper functions that I use to simplify processing of query
results a bit: <?php // For a simple query that should
return a single value, this returns just that value (or FALSE) so you can process it
immediately function db_result_single($result) { 	return
($row = mysql_fetch_row($result)) && isset($row[0]) ? $row[0] :
false; } // Returns the rows as an array of
rows // Providing a key_column gives you access to specific rows (e.g. if
(isset($result_array[$user_id])) ...) function db_result_array($result, $key_column
= null) { 	for ($array = array(); $row = mysql_fetch_assoc($result);
isset($row[$key_column]) ? $array[$row[$key_column]] = $row : $array[] =
$row); 	return
$array; } // Returns an array of a single column
of data that can optionally be keyed from second column (e.g. an array of user names keyed by user
id) function db_result_array_values($result) { 	for ($array
= array(); $row = mysql_fetch_row($result); isset($row[1]) ? $array[$row[1]] = $row[0] : $array[] =
$row[0]); 	return
$array; } ?> Naturally,
comments [to my email, not here] are welcome.
--was--
Just thought I'd share these helper functions that I use to simplify processing of query
results a bit:
<?php
// For a simple query that should return a single value, this returns just that value (or FALSE) so
you can process it immediately
function db_result_single($result) {
return ($row = mysql_fetch_row($result)) && isset($row[0]) ? $row[0] : false;
}
// Returns the rows as an array of rows
// Providing a key_column gives you access to specific rows (e.g. if
(isset($result_array[$user_id])) ...)
function db_result_array($result, $key_column = null) {
for ($array = array(); $row = mysql_fetch_assoc($result); isset($row[$key_column]) ?
$array[$row[$key_column]] = $row : $array[] = $row);
return $array;
}
// Returns an array of a single column of data that can optionally be keyed from second column (e.g.
an array of user names keyed by user id)
function db_result_array_values($result) {
for ($array = array(); $row = mysql_fetch_row($result); isset($row[1]) ? $array[$row[1]] = $row[0]
: $array[] = $row[0]);
return $array;
}
?>
Naturally, comments are welcome.
http://php.net/manual/en/function.mysql-fetch-array.php