简体   繁体   English

将php数组中的特定列插入mysql表

[英]Inserting specific columns from a php array into a mysql table

I have an array containing 42 records each having 6 fields returned by jquery post. 我有一个包含42条记录的数组,每条记录都有jquery post返回的6个字段。 I am using following method to split and organise data so that it can be inserted using an SQL insert statement. 我正在使用以下方法来拆分和组织数据,以便可以使用SQL插入语句将其插入。

$values = array();
foreach ($data as $rowValues) {
    foreach ($rowValues as $key => $rowValue) {
            }
 $values[] = "('" . implode("', '", $rowValues) . "','".$yr."','".$qtr."')";
   }

$query = "INSERT INTO table1 (field1, field2, field3, filed4)  VALUES " . implode (', ', $values);

Here the problem is the table1 has only 4 fields and I need only 4 columns in the array but the array contains 7 columns. 这里的问题是table1只有4个字段,我在数组中只需要4列,但是数组包含7列。 I want the other columns to update another table. 我希望其他列更新另一个表。 How can I do this? 我怎样才能做到这一点?

Solution 1: 解决方案1:

You can use array_slice to extract the first 2 elements of array: 您可以使用array_slice提取array的前两个元素:

$values = array();
foreach ($data as $rowValues) {
    $values[] = "('" . implode("', '", array_slice($rowValues, 0, 2)) . "','".$yr."','".$qtr."')";
}

$query = "INSERT INTO table1 (field1, field2, field3, filed4)  VALUES " . implode (', ', $values);

In your second query you can call 在第二个查询中,您可以致电

foreach ($data as $rowValues) {
    $values[] = "('" . implode("', '", array_slice($rowValues, 2)) ."')";
}

to get the remaining elements of your array. 获取数组的其余元素。

Solution 2: 解决方案2:

You can simply use the indices of the array: 您可以简单地使用数组的索引:

$values = array();
foreach ($data as $rowValues) {
    $values[] = "('".$rowValues[0]."','".$rowValues[2]."','".$rowValues[5]."','".$rowValues[6]."','".$yr."','".$qtr."')";
}

$query = "INSERT INTO table1 (field1, field2, field3, filed4)  VALUES " . implode (', ', $values);

And in your second query: 在第二个查询中:

$values = array();
foreach ($data as $rowValues) {
    $values[] = "('".$rowValues[0]."','".$rowValues[2]."','".$rowValues[3]."','".$rowValues[4]."','".$rowValues[5]."','".$rowValues[6]."','".$yr."','".$qtr."')";
}

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

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