简体   繁体   中英

Creating a single insert statement for multiple array values


I have a query about how to implement my use case.I have a set of arrays that I want to insert in the DB,but now I am confused how can I do it efficiently.I am using PHP and MySQL .Below is the use case:

$shareUrl = array();
$theInsertUrl = array();
$authKeyArray = array();

Above are the arrays I get after processing some information.Now I have to insert it into the DB,but instead of doing it one by one,I thought have a single insert would be better solution( Please correct if not ).
For multiple insert the values part of my SQL query must have

 ($shareUrl[0],$theInsertUrl[0],$authKeyArray[0]),($shareUrl[1],$theInsertUrl[1],$authKeyArray[1]),...

I thought of writing a for loop and create a multidimensional array like this

  for($i=0;$i<count_of_array;$i++){
        $multiArray[$i]['shareUrl'] = $shareUrl[0];
        $multiArray[$i]['theInsertUrl'] = $theInsertUrl[0];
        $multiArray[$i]['authKeyArray'] = $authKeyArray[0];
  }

But still it will be tedious to use this in the SQL query's values part as it accepts a format like this ('val1','val2'),('val1','val2') . I need suggestions on how can I go about implementing it? Is the above approach correct or is there a better solution OR should I go it with single insert statements?

just put everything as a string in the array and then implode it

$data= array();
for ($i = 0; $i < $size; $i++) {
    $data[] = "('".$mysqli->real_escape_string($array1[$i])."','".$mysqli->real_escape_string($array2[$i])."')";
}
if (sizeof($data) > 0) {
    $query = "INSERT INTO table (value1,value2) VALUES ".implode(",",$data).";");
    $mysqli->real_query($query)
}

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