Jump to content

[SOLVED] retriving data from a database


sinus

Recommended Posts

I have code that lists a number of people from a data and stores it array

 

// select people from first table who are part of group 1
$query= "SELECT personID FROM people WHERE groupID = 1";
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) {
$personid = $row["personID"];
}

 

The problem is I do not know  how many records it will return.

I then need to enter all these people into another table.

 

 

// add people to second table who are part of  group 1
$people = 0;
while ($people != $numrows) {
$query2 = "INSERT INTO people2 (peopleID, groupID) VALUES ('$personid',  '1')";
$queryaddperson = mysql_query($query2) or die(mysql_error());
$people++;
}

 

Rather than add every single person who is part of group 1 it just keeps adding the first person

over and over again to the people2 table.

 

Any help with this would be great.

 

Thanks

Sinus

 

Link to comment
https://forums.phpfreaks.com/topic/67146-solved-retriving-data-from-a-database/
Share on other sites

U dont know how many records it will return? U have those in $numrows!! Anyway, your problem is that the update snippet must either be inserted in the while($row = mysql_fetch_array){ } or make $personid an array:

 

$personid = array();
while ($row = mysql_fetch_array($result) {
     array_push($personid, $row['personID'];
}

 

foreach($personid as $value){
     $query2 = "INSERT INTO people2 (peopleID, groupID) VALUES ('$value',  '1')";
     $queryaddperson = mysql_query($query2) or die(mysql_error());
}

 

U got it know?

Hello

Thankyou for the replies.

 

So this

 


// select people from first table who are part of group 1
$query= "SELECT personID FROM people WHERE groupID = 1";
$result = mysql_query($query);
$numrows = mysql_num_rows($result);

while ($row = mysql_fetch_array($result) {
$personid = $row["personID"];

// add people to second table who are part of  group 1

$query2 = "INSERT INTO people2 (peopleID, groupID) VALUES ('$personid',  '1')";
$queryaddperson = mysql_query($query2) or die(mysql_error());


}

 

and this would do the exact same thing

 


// select people from first table who are part of group 1
$query= "SELECT personID FROM people WHERE groupID = 1";
$result = mysql_query($query);

$personid = array();
while ($row = mysql_fetch_array($result) {
array_push($personid, $row['personID'];
}

// add people to second table who are part of  group 1
foreach($personid as $value){
     $query2 = "INSERT INTO people2 (peopleID, groupID) VALUES ('$value',  '1')";
     $queryaddperson = mysql_query($query2) or die(mysql_error());
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.