Web Worm
Web Worm

Reputation: 2066

passing while() array to a variable out of while() in php

suppose i have a query

$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){
 $data = $row['data'];
}
$array = $data;

Now how can i get that each $data values out of while in an array() i.e $array

Upvotes: 3

Views: 2610

Answers (5)

Gitesh Dang
Gitesh Dang

Reputation: 182

$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){
   $array[] = $row['data'];
}

further u can use

$array['data']

and u can also use mysql_fetch_assoc($sql) instead mysql_fetch_array($sql)

Upvotes: 0

Garis M Suero
Garis M Suero

Reputation: 8170

You need to save each iteration object into a "new" object, so your code will look just like:

$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){
   $array[] = $row['data'];
}

please note the line:

   $array[] = $row['data'];

References:

Upvotes: 1

Sabeen Malik
Sabeen Malik

Reputation: 10880

Your $data variable is being overwritten during each iteration. So you need to turn it into $data[] and $data should be declared at the top, or you can just use $array[] as the other answer suggests, not sure why you put in the $data variable in their in the first place.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361585

$array = array();
$sql = mysql_query("SELECT * FROM table");

while ($row = mysql_fetch_array($sql)) {
    $array[] = $row['data'];
}

Upvotes: 8

Your Common Sense
Your Common Sense

Reputation: 157839

by adding each $row to array $data
for reference: http://php.net/types.array

Note that there is no such a thing as "while() array". There are just arrays only.

Upvotes: 1

Related Questions