using while and foreach

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
snpo123
Forum Commoner
Posts: 77
Joined: Sat Apr 17, 2004 6:31 pm

using while and foreach

Post by snpo123 »

I need to fetch results from a database, put them into an array, and then use a foreach loop to update a certian table. So far, this is what I have:

Code: Select all

<?php
include "mysql_connect.php";
$query = "select user_id from users";
$result = mysql_query ($query);
while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {
	
	echo "$row[0]<br>";
}


?>
Of course, all this does is give me all the user ids with a line break between them, as intended:

Code: Select all

1
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
What I want to do, however, is put each of those values into an array , then use foreach to insert them into a database. How would I go about doing this? Thanks.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php 
include "mysql_connect.php"; 
$query = "select user_id from users"; 
$result = mysql_query ($query); 
$data = array();
while (list($data[]) = mysql_fetch_row($result));

foreach($data as $row)
{
  echo print_r($row,true).'<br />';
  // you can put your inserts here...
}

?>
Post Reply