huz_akh
huz_akh

Reputation: 93

Merge Mysql Column output as comma seperated in php

I have a simple query with outputs only one column (rows number may change)

SELECT column1 as NUMBER WHERE column1 ...

Output,

NUMBER
  1
  2

I just want it as an array in PHP with them as comma seperated.

So I did,

$rows = array();
while ($row = mysql_fetch_row($result)) {
    $rows[] = $row;

and its working if I echo it with print_r

However because of some reason I cant get the plain values out of this array.

echo $rows[0] gives me the word 'Array'

echo implode(",", $rows); gives me 1Array',Array1

I tried

echo json_encode($rows[0]);

gives me

["1"]

I simply want 1,2

After a lot of different tries I gave up and added group_concat in the sql query. I just want to know what I did wrong.

Thanks.

Upvotes: 0

Views: 136

Answers (4)

Ravi Prakash Awasthi
Ravi Prakash Awasthi

Reputation: 133

try this

SELECT GROUP_CONCAT(`column1` SEPARATOR ',') AS number FROM table where....

Upvotes: 1

plaky93
plaky93

Reputation: 1

just make a simple amendment to your code:

$rows[] = $row;

into:

$rows[] = $row[0];

and use:

implode(", ", $rows[]);

Upvotes: 0

user2548054
user2548054

Reputation:

foreach($rows as $key => $value){

}

should do the trick, with an echo it will output the results as an associative array

Upvotes: 0

Steve
Steve

Reputation: 20469

mysql_fetch_row i returning a single element array. To have your desired output, only select the 1st element:

$rows = array();
while ($row = mysql_fetch_row($result)) {
    $rows[] = $row[0];

Upvotes: 0

Related Questions