0

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()?

2
  • 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 ] ) Commented Jan 12, 2012 at 15:02
  • @UdaySawant I want a column, not a row. Commented Jan 12, 2012 at 15:05

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Now if you moved right into the 22nd century and used PDO... ;o)
@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
1

you can do this with mysqli_fetch_all and array_column

$r = mysqli_query($c,"SELECT bug_name FROM bugs WHERE color='red'");
$bug_names = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"bug_name");

Comments

0

Nothing like that built in, you will need to do this manually.

Comments

-1

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

I wanted to avoid that iterating, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.