简体   繁体   English

将表的结果插入到具有两个foreach循环的另一个表中

[英]Inserting result of a table into another table with two foreach loops

I am trying to get the result of a table and insert it into another table. 我试图获取表的结果并将其插入另一个表。 The results are user id's. 结果是用户ID。 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-select语句中执行此操作?

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: 为了回答评论中提出的问题,可以选择'validated'值作为文字:

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']; 在使用foreach($select as $index => $rs)迭代第一个查询的结果时,使用$users = $rs['id'];$users设置$users结果的每一行的$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. 在循环结束时, $users将包含最后一行的id,因为它每次都被覆盖。 It's not iterable (it's an int), so foreach ($users as $row){ doesn't make sense. 它不是可迭代的(它是一个int),所以foreach ($users as $row){没有意义。

You probably meant to do $users[] = $rs['id']; 你可能打算做$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. 但是,如果您只是将它们全部插入,那么您可以在一个查询中执行此操作,就像其他答案所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM