简体   繁体   中英

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. I am using following method to split and organise data so that it can be inserted using an SQL insert statement.

$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. I want the other columns to update another table. How can I do this?

Solution 1:

You can use array_slice to extract the first 2 elements of 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:

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."')";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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