I am trying to make a function which converts a mysql query result in to an array
In the function below i’m assuming to have fields isbn, title and rank but this will not always be the case.
Is there a way to retrieve a fields name along with the value without actually knowing any of this information prior? so that this function can be used with any mysql query result.
function
function mysqlToArray($result){
$arr = array();
$numRows = mysql_num_rows($result);//count
if($numRows>0){
for($i=0; $i<$numRows; $i++){
$arr[] = array(
"isbn" => mysql_result($result, $i, "isbn"),
"title" => mysql_result($result, $i, "title"),
"rank" => mysql_result($result, $i, "rank"),
);
}
}
return $arr;
}
example in use
function getProfitableBooks(){
$q = "SELECT isbn, title, rank FROM ".TBL_BOOKS;
$result = mysql_query($q, $this->connection);
if(!$result || (mysql_numrows($result) < 1)){
return null;
}
return $this->mysqlToArray($result);
}
There is a great PHP function for this
mysql_fetch_arrayYou can view examples mysql_fetch_array in the PHP manual.