“如何连接两个数组的数据并插入到mysql数据库中?”

时间:2019-01-04 06:30:53

标签: mysql arrays concatenation

我有两个mysql查询,可将数据插入两个不同的表中。查询结果如下:

  1. INSERT INTO table1 (ans1,ans2,ans3,ans4,ans5) VALUES (0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)

  2. INSERT INTO table2 (uid,cid,sid) VALUES (1,abc,123),(2,def,456),(3,ghi,789)

如何连接这两个结果,使输出看起来像

INSERT INTO table3 (uid,cid,sid,ans1,ans2,ans3,ans4,ans5)
VALUES
    (1,abc,123,0,0,0,0,0),
    (2,def,456,1,1,1,0,0),
    (3,ghi,789,0,0,0,0,0)

1 个答案:

答案 0 :(得分:1)

我这样想:

<?php
//First we need connect to database
$server = "localhost";
$Userdb = "admin";
$Passworddb = "password";
$database = "db";
$conn = mysqli_connect($server, $Userdb, $Passworddb, $database);
mysqli_set_charset($conn, "utf8");

//Getting values - for this example it is static
//For concate we need values as array => explode()
$colums1 = "ans1,ans2,ans3,ans4,ans5";
$values1 = explode("),(", substr("(0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)", 1, -1));
$colums2 = "uid,cid,sid";
$values2 = explode("),(", substr("(1,abc,123),(2,def,456),(3,ghi,789)", 1, -1));

//Query for table1
$command = "INSERT INTO table1 (".$colums1.") VALUES ".$values1;
mysqli_query($conn, $command) or die(mysqli_error($conn));

//Query for table2
$command = "INSERT INTO table2 (".$colums2.") VALUES ".$values2;
mysqli_query($conn, $command) or die(mysqli_error($conn));

//We need to concate values so =>
//=> For every index of $values1 add at same index into $values3 concated $values1 and $values2

$values3 = array();
for ($x = 0; $x <= count($values1); $x++) { 
    $values3[$x] = "(".$values2[x].",".$values1[$x].")";
}

//Query for table3
$command = "INSERT INTO table3 (".$colums2.",".$colums1.") VALUES (".implode("),(", $values3).")";
mysqli_query($conn, $command) or die(mysqli_error($conn));
?>

我认为这应该有效(一个人都不知道:))