I am trying to get the result of a table and insert it into another table. The results are user id's. This code should work, but it doesn't.
$query1 = "SELECT id FROM users";
$select1 = $db->prepare($query1);
$select1->execute(array());
foreach($select as $index => $rs) {
$users = $rs['id'];
// the results are 1,2,3,4,5,6,7,8... (the user id's)
}
// Here below, I want to add the results into another table...
foreach ($users as $row){
$query2 = "INSERT INTO validateuser (userid) VALUES (".$row.")";
$select2 = $db->prepare($query2);
$select2->execute(array());
}
This seems over-complicated to me. Why not let the database do what databases do best - handle data, and perform this in a single insert-select statement?
INSERT INTO validateuser (userid)
SELECT id FROM users
EDIT:
To answer the concern raised in the comments, the 'validated'
value could be selected as a literal:
INSERT INTO validateuser (userid, validated)
SELECT id, 'validated' FROM users
As you iterate the results of the first query with foreach($select as $index => $rs)
, you set $users
to the id of each row of the results with $users = $rs['id'];
.
At the end of your loop, $users
will contain the id of the last row because it's being overwritten each time. It's not iterable (it's an int), so foreach ($users as $row){
doesn't make sense.
You probably meant to do $users[] = $rs['id'];
instead. But if you're just inserting them all, you might as well just do it in one query like the other answer suggests.