doupeng6890 2014-01-17 08:41
浏览 80
已采纳

为多个数组值创建单个insert语句


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?

  • 写回答

1条回答 默认 最新

  • dqp21271 2014-01-17 09:05
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题