开发者

Populate PHP Array from While Loop

If I am fetching data from a MySQL database and using a while loop to iterate through the data how would I add each one to array?

$result = mysql_query(开发者_JAVA技巧"SELECT * FROM `Departments`");
while($row = mysql_fetch_assoc($result))
{

}


Build an array up as you iterate with the while loop.

$result = mysql_query("SELECT * FROM `Departments`");
$results = array();
while($row = mysql_fetch_assoc($result))
{
   $results[] = $row;
}

Alternatively, if you used PDO, you could do this automatically.


This will do the trick:

$rows = array();
$result = mysql_query("SELECT * FROM `Departments`");
while($row = mysql_fetch_assoc($result))
{
  $rows[] = $row;
}


This has been one of the fastest ways for me to create (multi-dimensional) arrays. I'm not sure if you want all of your results smooshed into one array or not.

// Read records
$query = "SELECT * FROM `Departments`"; 
$query = mysql_query($query);

// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($query); $i++) ;

// Delete last empty one
array_pop($array);

You can use print_r($array) to see the results.


If you have multiple columns in your Departments table and you want to save in different array.

$result = mysql_query("SELECT * FROM `Departments`");
$dept_id = array();
$dept_name=array();
while($row = mysql_fetch_assoc($result))
{
//fetches and store all results in id column on your departments table
$dept_id= $row['id'];
//fetches and store all results in name column on your departments table    
$dept_name=$row['name'];
}


my fav is the following;

$result=odbc_exec($conn,$sql);
if ($result) {
    while($found_results[] = odbc_fetch_array($result)) { } 
    array_pop($found_results); //pop off the empty line from while loading
}

you dont need to pop the last line, but it does leave a blank if you omit it. works the same for mysql obviously.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜