I'm selecting a single column from a MySQL table with mysql_query(). Is there already a function for getting the results into an array, or will I have to iterate through all the results with something like mysql_fetch_array()?
4 Answers
You have to iterate.
If you moved into the 21st century, and used mysqli, there's a mysqli_fetch_all() function.... and you'd be able to use prepared statements
2 Comments
deceze
Now if you moved right into the 22nd century and used PDO... ;o)
Mark Baker
@deceze - I edited it.... originally I'd said 20th century, with a comment about PDO.... but decided that 1 step at a time might be kinder on the OP's sanity
you can use mysql_result function still need to do some coding
mysql_result($result,$row_num,$fieldname) ;
retrieves $row_num 'th columes $field_name field .
and following snippet can be taken as an example
$con =mysql_connect($host,$uname,$passwd);
mysql_select_db($dbname,$con);
$result = mysql_query($query,$con);
$arr = array();
$numrows = mysql_num_rows($result);
for($i=0;$i<$numrows;$i++) {
$arr[] = mysql_result($result,$i,$fieldname);
}
this stores every elements of column $fieldname to array $arr
1 Comment
Andreas
I wanted to avoid that iterating, though.
mysql_fetch_array()returns an array itself. you can set array to be an associative or numeric.array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )