[英]How to transfer several rows from one table to other table (SQL)
I have two tables TableA
and TableB
with colums id
, login
, pass
.我有两个表TableA
和TableB
与列id
, login
, pass
。 Also I have a php array: $array = [1,3,5]
.我还有一个 php 数组: $array = [1,3,5]
。 How can I transfer rows from TableA
to TableB
where id
equal each value of my array?如何将行从TableA
传输到TableB
,其中id
等于数组的每个值? id
is autoincremented and must be unique. id
是自动递增的,并且必须是唯一的。 In my head it looks like this :在我的脑海中它看起来像这样:
INSERT INTO TableB (`login`, `pass`)
SELECT `login`, `pass` FROM TableA WHERE `id` = $array[0]
AND `id` = $array[1] AND `id` = $array[2];
But it does not work但它不起作用
Is there any chances to do it in cycle using WHILE
?有没有机会使用WHILE
循环进行?
You can use a statement such as this:您可以使用如下语句:
$ids = [1,3,5];
$query = "INSERT INTO `TableB` (`login`, `pass`) SELECT `login`,`pass` FROM `TableA` WHERE `id` IN (".implode(",", $ids).");";
Although: You should be using prepared statements and parameters for this, this answer is just meant to show the syntax.虽然:您应该为此使用准备好的语句和参数,但此答案仅用于显示语法。
it is easy let's say you are using mysqli:假设您正在使用 mysqli,这很容易:
$query= "SELECT * FROM TableA limit 3";
//takes first 3 rows from TableA
//$con being the connection string in config file
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
//takes each row by row
$username = $row['username'];
$password = $row['password'];
//now that we initiated variables the sql query
$query1 = "INSERT INTO TableB (username, password) VALUES ('$username', '$password')";
mysqli_query($con,$query1);
}
Hope this helps希望这可以帮助
EDIT: I just read that it should have an array so you should change your query to this:编辑:我刚刚读到它应该有一个数组,因此您应该将查询更改为:
for($i=0; $i<count(array), $i++){
$query= "SELECT * FROM TableA WHERE ID = '$array[i]'";
//$con being the connection string in config file
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result){
//takes each row by row
$username = $row['username'];
$password = $row['password'];
//now that we initiated variables the sql query
$query1 = "INSERT INTO TableB (username, password) VALUES ('$username', '$password')";
mysqli_query($con,$query1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.