insert multiple rows via a php array into mysql

后端 未结 12 1522
自闭症患者
自闭症患者 2020-11-21 22:35

I\'m passing a large dataset into a MySQL table via PHP using insert commands and I\'m wondering if its possible to insert approximately 1000 rows at a time via a query othe

12条回答
  •  长发绾君心
    2020-11-21 23:26

    I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl), table-field ($insertFieldsArr) against your inserting data, data array ($arr).

    insert_batch('table',array('field1','field2'),$dataArray);
    
        function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array(); 
        foreach( $arr as $row ) {
            $strVals='';
            $cnt=0;
            foreach($insertFieldsArr as $key=>$val){
                if(is_array($row)){
                    $strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
                }
                else{
                    $strVals.="'".mysql_real_escape_string($row).'\',';
                }
                $cnt++;
            }
            $strVals=rtrim($strVals,',');
            $sql[] = '('.$strVals.')';
        }
    
        $fields=implode(',',$insertFieldsArr);
        mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
    }
    

提交回复
热议问题