我有两个表TableA
和TableB
,其中包含列id
,login
,pass
。我还有一个php数组:$array = [1,3,5]
。如何将行从TableA
传输到TableB
,其中id
等于我的数组的每个值? id
是自动增量的,必须是唯一的。
在我看来,它看起来像这样:
INSERT INTO TableB (`login`, `pass`)
SELECT `login`, `pass` FROM TableA WHERE `id` = $array[0]
AND `id` = $array[1] AND `id` = $array[2];
但它不起作用
是否有机会使用WHILE
进行循环?
答案 0 :(得分:2)
您可以使用如下语句:
$ids = [1,3,5];
$query = "INSERT INTO `TableB` (`login`, `pass`) SELECT `login`,`pass` FROM `TableA` WHERE `id` IN (".implode(",", $ids).");";
虽然:您应该为此使用预准备语句和参数,但这个答案只是为了显示语法。
答案 1 :(得分:1)
很容易让你说你正在使用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);
}
希望这有帮助
编辑: 我刚刚读到它应该有一个数组,所以你应该改变你的查询:
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);
}
}