Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中使用Foreach将数据导入DB的最佳方式是什么?_Php_Sql - Fatal编程技术网

在php中使用Foreach将数据导入DB的最佳方式是什么?

在php中使用Foreach将数据导入DB的最佳方式是什么?,php,sql,Php,Sql,谢谢你的关注。 我是php和MySQL的新手,有一个项目是SimpleFlow。 这里我有一个问题,想知道确切的情况。 所以,在php中使用foreach将数据添加到db中时,为了提高代码性能,最好的方法是什么 这里有一个例子 第一例 foreach ($data as $key=>$item){//start for each loop $id = $item['id']; $Name = $item['adsname']; if (!$id || !$bingAdsName) {

谢谢你的关注。 我是php和MySQL的新手,有一个项目是SimpleFlow。 这里我有一个问题,想知道确切的情况。 所以,在php中使用foreach将数据添加到db中时,为了提高代码性能,最好的方法是什么

这里有一个例子

  • 第一例

    foreach ($data as $key=>$item){//start for each loop
    $id = $item['id'];
    $Name = $item['adsname'];
    if (!$id || !$bingAdsName) {
        continue;
    }
    $sql="select* from table name ";
    //$dbData = ...  //fetch all db data.
    //And below it will compare dbdata and the above id&Name with some 
    condition and add to db these value.
    }//end foreach loop
    
  • 第二种情况

    foreach ($data as $key=>$item){
        $id = $item['id'];
        $Name = $item['adsname'];
        if (!$id || !$bingAdsName) {
           continue;
        }
        $sql="select* from table name where id='".$id."' AND name='".$Name."'";
        $existData= ...;
        if(!existData){
            continue;
        }
        $sql="INSERT INTO table name(id, name,)
        VALUES ('".$id."', '".$name."'); ";
        //here insert id& value into db;
    }
    
  • 所以在第一种情况下,我将只调用一个db连接,但它将处理二维foreach

    在第二种情况下,它将调用db connection来计算
    $data
    的次数

    所以我想知道什么是减少代码运行时间以提高性能的最佳方法。
    谢谢。

    在我看来,您的
    第二种情况
    是一种更有效的方法,因为用简单的php整理或过滤数据会使您的应用程序慢得多。MySQL在这种情况下非常强大和高效。因此,您应该在过滤数据时应用MySQL,以使您的应用程序更高效。


    有关更多信息,您可以参考
    谢谢

    您的代码在性能方面存在高风险,这里最好使用一个准备好的语句。您好,@ZainFarooq,这只是示例sql,我使用PDO来避免sql注入。您好,@Dormilich,您能告诉我这里的确切含义吗?在我看来,第二种情况更有效