note 108765 modified in function.mysql-fetch-array by danbrown

From: 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&#39;d share these helper functions that I use to simplify processing of query results a bit:&#13;&#10;&#60;?php&#13;&#10;// For a simple query that should return a single value, this returns just that value (or FALSE) so you can process it immediately&#13;&#10;function db_result_single($result) {&#13;&#10;&#9;return ($row = mysql_fetch_row($result)) &#38;&#38; isset($row[0]) ? $row[0] : false;&#13;&#10;}&#13;&#10;&#13;&#10;// Returns the rows as an array of rows&#13;&#10;// Providing a key_column gives you access to specific rows (e.g. if (isset($result_array[$user_id])) ...)&#13;&#10;function db_result_array($result, $key_column = null) {&#13;&#10;&#9;for ($array = array(); $row = mysql_fetch_assoc($result); isset($row[$key_column]) ? $array[$row[$key_column]] = $row : $array[] = $row);&#13;&#10;&#9;return $array;&#13;&#10;}&#13;&#10;&#13;&#10;// 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)&#13;&#10;function db_result_array_values($result) {&#13;&#10;&#9;for ($array = array(); $row = mysql_fetch_row($result); isset($row[1]) ? $array[$row[1]] = $row[0] : $array[] = $row[0]);&#13;&#10;&#9;return $array;&#13;&#10;}&#13;&#10;?&#62;&#13;&#10;&#13;&#10;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

« previous php.notes (#188174) next »