insert multiple rows via a php array into mysql

后端 未结 12 1523
自闭症患者
自闭症患者 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

    You could prepare the query for inserting one row using the mysqli_stmt class, and then iterate over the array of data. Something like:

    $stmt =  $db->stmt_init();
    $stmt->prepare("INSERT INTO mytbl (fld1, fld2, fld3, fld4) VALUES(?, ?, ?, ?)");
    foreach($myarray as $row)
    {
        $stmt->bind_param('idsb', $row['fld1'], $row['fld2'], $row['fld3'], $row['fld4']);
        $stmt->execute();
    }
    $stmt->close();
    

    Where 'idsb' are the types of the data you're binding (int, double, string, blob).

    0 讨论(0)
  • 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));
    }
    
    0 讨论(0)
  • 2020-11-21 23:28
    $query= array(); 
    foreach( $your_data as $row ) {
        $query[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
    }
    mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $query));
    
    0 讨论(0)
  • 2020-11-21 23:29

    You could always use mysql's LOAD DATA:

    LOAD DATA LOCAL INFILE '/full/path/to/file/foo.csv' INTO TABLE `footable` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' 
    

    to do bulk inserts rather than using a bunch of INSERT statements.

    0 讨论(0)
  • 2020-11-21 23:31

    Although it is too late to answer this question. Here are my answer on the same.

    If you are using CodeIgniter then you can use inbuilt methods defined in query_builder class.

    $this->db->insert_batch()

    Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

    $data = array(
        array(
                'title' => 'My title',
                'name' => 'My Name',
                'date' => 'My date'
        ),
        array(
                'title' => 'Another title',
                'name' => 'Another Name',
                'date' => 'Another date'
        )
    );
    
    $this->db->insert_batch('mytable', $data);
    // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')
    

    The first parameter will contain the table name, the second is an associative array of values.

    You can find more details about query_builder here

    0 讨论(0)
  • 2020-11-21 23:32

    I have created a class that performs multi-line that is used as follows:

    $pdo->beginTransaction();
    $pmi = new PDOMultiLineInserter($pdo, "foo", array("a","b","c","e"), 10);
    $pmi->insertRow($data);
    // ....
    $pmi->insertRow($data);
    $pmi->purgeRemainingInserts();
    $pdo->commit();
    

    where the class is defined as follows:

    class PDOMultiLineInserter {
        private $_purgeAtCount;
        private $_bigInsertQuery, $_singleInsertQuery;
        private $_currentlyInsertingRows  = array();
        private $_currentlyInsertingCount = 0;
        private $_numberOfFields;
        private $_error;
        private $_insertCount = 0;
    
        /**
         * Create a PDOMultiLine Insert object.
         *
         * @param PDO $pdo              The PDO connection
         * @param type $tableName       The table name
         * @param type $fieldsAsArray   An array of the fields being inserted
         * @param type $bigInsertCount  How many rows to collect before performing an insert.
         */
        function __construct(PDO $pdo, $tableName, $fieldsAsArray, $bigInsertCount = 100) {
            $this->_numberOfFields = count($fieldsAsArray);
            $insertIntoPortion = "REPLACE INTO `$tableName` (`".implode("`,`", $fieldsAsArray)."`) VALUES";
            $questionMarks  = " (?".str_repeat(",?", $this->_numberOfFields - 1).")";
    
            $this->_purgeAtCount = $bigInsertCount;
            $this->_bigInsertQuery    = $pdo->prepare($insertIntoPortion.$questionMarks.str_repeat(", ".$questionMarks, $bigInsertCount - 1));
            $this->_singleInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks);
        }
    
        function insertRow($rowData) {
            // @todo Compare speed
            // $this->_currentlyInsertingRows = array_merge($this->_currentlyInsertingRows, $rowData);
            foreach($rowData as $v) array_push($this->_currentlyInsertingRows, $v);
            //
            if (++$this->_currentlyInsertingCount == $this->_purgeAtCount) {
                if ($this->_bigInsertQuery->execute($this->_currentlyInsertingRows) === FALSE) {
                    $this->_error = "Failed to perform a multi-insert (after {$this->_insertCount} inserts), the following errors occurred:".implode('<br/>', $this->_bigInsertQuery->errorInfo());
                    return false;
                }
                $this->_insertCount++;
    
                $this->_currentlyInsertingCount = 0;
                $this->_currentlyInsertingRows = array();
            }
            return true;
        }
    
        function purgeRemainingInserts() {
            while ($this->_currentlyInsertingCount > 0) {
                $singleInsertData = array();
                // @todo Compare speed - http://www.evardsson.com/blog/2010/02/05/comparing-php-array_shift-to-array_pop/
                // for ($i = 0; $i < $this->_numberOfFields; $i++) $singleInsertData[] = array_pop($this->_currentlyInsertingRows); array_reverse($singleInsertData);
                for ($i = 0; $i < $this->_numberOfFields; $i++)     array_unshift($singleInsertData, array_pop($this->_currentlyInsertingRows));
    
                if ($this->_singleInsertQuery->execute($singleInsertData) === FALSE) {
                    $this->_error = "Failed to perform a small-insert (whilst purging the remaining rows; the following errors occurred:".implode('<br/>', $this->_singleInsertQuery->errorInfo());
                    return false;
                }
                $this->_currentlyInsertingCount--;
            }
        }
    
        public function getError() {
            return $this->_error;
        }
    }
    
    0 讨论(0)
提交回复
热议问题