Dump the contents of the database as insert statements

@return string
975364
public function dump()
	{
		$pdo = $this->pdo();

		$sql = '';

		foreach ($this->list_tables() as $table)
		{
			$query = $pdo->query("SELECT * FROM `{$table}`");

			while ($row = $query->fetch(\PDO::FETCH_NUM)) 
			{
				$values = array();

				foreach ($row as $column) 
				{
					$values[] = is_null($column) ? 'NULL' : $pdo->quote($column);
				}

				$sql .= "INSERT INTO `{$table}` VALUES (".join(',', $values). ");\n";
			}
		}

		return $sql;
	}
921869
protected function insertRow()
    {   
        $assignedValues = $this->getAssignedValues();

        $columns = implode(', ', $assignedValues['columns']);
        $values = '\''.implode('\', \'', $assignedValues['values']).'\'';

        $tableName = $this->getTableName($this->className);

        $connection = Connection::connect();

        $insert = $connection->prepare('insert into '.$tableName.'('.$columns.') values ('.$values.')');
        var_dump($insert);
        if ($insert->execute()) { 
            return 'Row inserted successfully'; 
        } else { 
            var_dump($insert->errorInfo()); 
        } 
    }
900633
public function backupStructure(): string
	{
		$string = [];

		// Get databases
		$dbs = $this->getDriver()->getDbs();

		foreach($dbs as &$d)
		{
			// Skip built-in dbs
			// @codeCoverageIgnoreStart
			if ($d === 'mysql')
			{
				continue;
			}
			// @codeCoverageIgnoreEnd

			// Get the list of tables
			$tables = $this->getDriver()->driverQuery("SHOW TABLES FROM `{$d}`", TRUE);

			foreach($tables as $table)
			{
				$array = $this->getDriver()->driverQuery("SHOW CREATE TABLE `{$d}`.`{$table}`", FALSE);
				$row = current($array);

				if ( ! isset($row['Create Table']))
				{
					continue;
				}


				$string[] = $row['Create Table'];
			}
		}

		return implode("\n\n", $string);
	}
796370
public function dump()
    {
        foreach ($this->children as $child) {
            $this->logger->info(sprintf('[dizda-backup] Dumping %s database', $child->getName()));
            $child->dump();
        }
    }
883776
public function toSql(): array
    {
        if (!$this->into) {
            throw new SqlException('Undefined INSERT table.');
        }

        if (!$this->columns and !$this->select) {
            throw new SqlException('Undefined INSERT columns.');
        }

        $params = [];

        $sql = ['INSERT INTO', $this->into, '(' . implode(', ', $this->columns) . ')'];

        if ($this->select) {
            $select = $this->prepareSelect($this->select);

            $sql[] = $select['sql'];

            $params = array_merge($params, $select['params']);
        } else {
            $columnsCount = count($this->columns);

            $valuesCount = count($this->values);

            if ($columnsCount !== $valuesCount) {
                throw new SqlException('INSERT values count does not match.'
                    . ' Expected ' . $columnsCount . ', got ' . $valuesCount . '.');
            }

            $sql[] = 'VALUES ' . $this->prepareBindKeys($this->values);

            $params = array_merge($params, $this->values);
        }

        $sql = implode(' ', $sql);

        return [$sql, $params];
    }
265357
public function getSQLForInsert()
    {
        $columns = array_map(function ($column) {
            return $this->getQuotedName($column);
        }, array_keys(current($this->sqlParts['values'])));

        $values = [];
        foreach ($this->sqlParts['values'] as $part) {
            $record = array_map(function ($value) {
                if ($value instanceof ToSqlInterface) {
                    return $value->toSQL();
                }

                return $this->getAdapter()->getSqlType($value);
            }, $part);

            $values[] = '('.implode(', ', $record).')';
        }

        $table = $this->getQuotedName($this->sqlParts['from']['table']);

        return sprintf(
            'INSERT INTO %s (%s) VALUES %s',
            $table,
            implode(', ', $columns),
            implode(', ', $values)
        );
    }
321877
public function save()
    {
        $sQuery = $this->_prepare();

        if (preg_match('/INSERT INTO/i', $sQuery)) {

            $oDb = self::connect();

            if (!$oDb->exec($sQuery)) {
                error_log($sQuery."\n".print_r($oDb->errorInfo(), true));
            }

            $this->flush();
            return $oDb->lastInsertId();
        }
        else {

            $this->flush();

            if ($this->_mWhere instanceof Where) { $this->_mWhere->flush(); }

            return self::connect()->exec($sQuery);
        }

    }
507893
function insert() {
		$args=[];
		$actr=0;
		$nctr=0;
		$fields='';
		$values='';
		$filter='';
		$pkeys=[];
		$nkeys=[];
		$ckeys=[];
		$inc=NULL;
		foreach ($this->fields as $key=>$field)
			if ($field['pkey'])
				$pkeys[$key]=$field['previous'];
		if (isset($this->trigger['beforeinsert']) &&
			\Base::instance()->call($this->trigger['beforeinsert'],
				[$this,$pkeys])===FALSE)
			return $this;
		foreach ($this->fields as $key=>&$field) {
			if ($field['pkey']) {
				$field['previous']=$field['value'];
				if (!$inc && $field['pdo_type']==\PDO::PARAM_INT &&
					empty($field['value']) && !$field['nullable'])
					$inc=$key;
				$filter.=($filter?' AND ':'').$this->db->quotekey($key).'=?';
				$nkeys[$nctr+1]=[$field['value'],$field['pdo_type']];
				$nctr++;
			}
			if ($field['changed'] && $key!=$inc) {
				$fields.=($actr?',':'').$this->db->quotekey($key);
				$values.=($actr?',':'').'?';
				$args[$actr+1]=[$field['value'],$field['pdo_type']];
				$actr++;
				$ckeys[]=$key;
			}
		}
		if ($fields) {
			$add=$aik='';
			if ($this->engine=='pgsql' && !empty($pkeys)) {
				$names=array_keys($pkeys);
				$aik=end($names);
				$add=' RETURNING '.$this->db->quotekey($aik);
			}
			$lID=$this->db->exec(
				(preg_match('/mssql|dblib|sqlsrv/',$this->engine) &&
				array_intersect(array_keys($pkeys),$ckeys)?
					'SET IDENTITY_INSERT '.$this->table.' ON;':'').
				'INSERT INTO '.$this->table.' ('.$fields.') '.
				'VALUES ('.$values.')'.$add,$args
			);
			if ($this->engine=='pgsql' && $lID && $aik)
				$this->_id=$lID[0][$aik];
			elseif ($this->engine!='oci')
				$this->_id=$this->db->lastinsertid();
			// Reload to obtain default and auto-increment field values
			if ($reload=(($inc && $this->_id) || $filter))
				$this->load($inc?
					[$inc.'=?',$this->db->value(
						$this->fields[$inc]['pdo_type'],$this->_id)]:
					[$filter,$nkeys]);
			if (isset($this->trigger['afterinsert']))
				\Base::instance()->call($this->trigger['afterinsert'],
					[$this,$pkeys]);
			// reset changed flag after calling afterinsert
			if (!$reload)
				foreach ($this->fields as $key=>&$field) {
					$field['changed']=FALSE;
					$field['initial']=$field['value'];
					unset($field);
				}
		}
		return $this;
	}
626373
public function dump()
    {
        $isFirst = $this->dumpFlag('first', $this->isFirst());
        $isCurrent = $this->dumpFlag('current', $this->isCurrent());
        $isPrevious = $this->dumpFlag('prev', $this->isPrevious());
        $isNext = $this->dumpFlag('next', $this->isNext());
        $isLast = $this->dumpFlag('last', $this->isLast());

        $number = str_pad((string)$this->number(), 10, ' ', STR_PAD_LEFT);

        $flags = "$isCurrent|$isFirst|$isLast|$isPrevious|$isNext";

        $string = str_pad("'$this'", 10, ' ', STR_PAD_LEFT);

        $offset = str_pad((string)$this->getOffset(), 20, ' ', STR_PAD_LEFT);

        return "Page #$number $string offset:$offset flags:$flags";
    }
336302
public function dumpBody()
    {
        $lines = file($this->getFileName());
        $startLine = $this->getStartLine();
        $endLine = $this->getEndLine();
        $lines[$startLine - 1] = explode('{', $lines[$startLine - 1]);
        $lines[$startLine - 1] = end($lines[$startLine - 1]);
        $end = mb_strrpos($lines[$endLine - 1], '}');
        if ($end !== false) {
            $lines[$endLine - 1] = mb_substr($lines[$endLine - 1], 0, $end);
        }
        $lines[$endLine - 1] .= '}';

        $code = '';
        for ($line = $startLine - 1; $line < $endLine; $line++) {
            $code .= $lines[$line];
        }

        return $code;
    }
426759
protected function doInsert()
    {
        //check if there is an error from previous function execution
        if (static::$response["status"] == "error") {
           return static::terminate(static::$response);
        }
        //convert each columns to ? parameter
        $columnParam = array_map(function () {
            return '?';
        }, $this->values);


        $sql = /** @lang sql */
            'INSERT INTO ' . self::$table .
            ' (' . $this->columns .
            ') VALUES(' . implode(',', $columnParam) . ')';

            $ext=array_map(function ($column){
                return $column.'=VALUES('.$column.')';
            },explode(',',$this->columns));
            if($this->updateOrInsert){ //if update when duplicate is found is set to true
                $sql.=' ON DUPLICATE KEY UPDATE '.implode(',',$ext);
            }

        try {
            $stm = Connect::getConn()->prepare($sql);
        } catch (Exception $e) {
            static::$response["status"] = "error";
            static::$response["response"] = $e->getMessage();
            static::$response["code"] = $e->getCode();
           return static::terminate(static::$response);
        }

        try {
            $stm->execute($this->values);

            static::$response["status"] = "success";
            static::$response["response"] = "success";
            static::$response["code"] = 200;

            return static::terminate(static::$response);
        } catch (Exception $e) {
            static::$response["status"] = "error";
            static::$response["response"] = $e->getMessage();
            static::$response["code"] = $e->getCode();
            return static::terminate(static::$response);
        }
    }
166567
private function insert()
    {
        $insert = $this->dsql();

        // Performs the actual database changes. Throw exception if problem occurs
        foreach ($this->elements as $name => $f) {
            if ($f instanceof Field) {
                if (!$f->editable() && !$f->system()) {
                    continue;
                }
                if (!isset($this->dirty[$name]) && $f->defaultValue() === null) {
                    continue;
                }

                $f->updateInsertQuery($insert);
            }
        }
        $this->hook('beforeInsert', array(&$insert));
        //delayed is not supported by INNODB, but what's worse - it shows error.
        //if($this->_save_as===false)$insert->option_insert('delayed');
        $id = $insert->insert();
        if ($id == 0) {
            // no auto-increment column present
            $id = $this->get($this->id_field);

            if ($id === null && $this->_save_as !== false) {
                throw $this->exception('Please add auto-increment ID column to your table or specify ID manually');
            }
        }
        $res = $this->hook('afterInsert', array($id));
        if ($res === false) {
            return $this;
        }

        if ($this->_save_as === false) {
            return $this->unload();
        }
        if ($this->_save_as) {
            $this->unload();
        }
        $o = $this->_save_as ?: $this;

        if ($this->fast && !$this->_save_as) {
            $this[$this->id_field] = $this->id = $id;

            return $this;
        }
        $res = $o->tryLoad($id);
        if (!$res->loaded()) {
            throw $this->exception('Saved model did not match conditions. Save aborted.');
        }

        return $res;
    }
1371781
public function save()
	{
		$sQuery = $this->_prepare();

		if (preg_match('/INSERT INTO/i', $sQuery)) {

			$oDb = self::connect();
			$oDb->exec($sQuery);
			$this->flush();
			return $oDb->lastInsertId();
		}
		else {

			$this->flush();

			if ($this->_mWhere instanceof Where) { $this->_mWhere->flush(); }

			return self::connect()->exec($sQuery);
		}

	}
988801
public static function dump()
    {
        $modules = array();
        static::select('name', 'type', 'updated_at')->get()->each(function($module) use (&$modules) {
            if (!isset($modules[ $module->type ])) {
                $modules[ $module->type ] = array();
            }
            $modules[ $module->type ][ $module->name ] = $module->updated_at->timestamp;
        });
        return $modules;
    }
489150
public function dbInsert() {
		BLog::addToLog('[Items.Item.' . $this->tableName . ']: Inserting data...');
		if (!$db = \Brilliant\BFactory::getDBO()) {
			return false;
		}
		//Forming query...
		$this->modified = new \Brilliant\BDateTime();
		//For import we need ability to set `created`
		if (empty($this->created)) {
			$this->created = new \Brilliant\BDateTime();
		}
		$qr = $this->dbInsertQuery();
		//Running query...
		$q = $db->query($qr);
		if (empty($q)) {
			return false;
		}
		$this->{$this->primaryKeyName} = $db->insertId();
		$this->isNew = false;
		//Updating cache...
		$this->updateCache();
		//Return result
		return true;
	}
22007
public function backupAction()
    {
        $filter = $this->getSearchFilter();
        $model = $this->getModel();

        $tables = $model->load();
        $allTables = [];
        $noDataTables = [];
        foreach($tables as $table) {
            if ($table['type'] == 'view' && (!array_key_exists('include_views', $filter) || $filter['include_views'] != '1')) {
                continue;
            }
            $allTables[] = $table['name'];
            if ($table['respondentData'] === true && (!array_key_exists('include_respondent_data', $filter) || $filter['include_respondent_data'] != '1')) {
                $noDataTables[] = $table['name'];
            }
        }

        $filename = $this->getBackupFilename($filter);
        $dbConfig = $this->getDatabaseConfig();
        $dumpSettings = [
            'include-tables' => $allTables,
            'no-data' => $noDataTables,
            'single-transaction' => true,
            'lock-tables' => false,
            'add-locks' => false,
            'add-drop-table' => true,
        ];

        ini_set('max_execution_time', 300);

        try {
            $dump = new \Ifsnop\Mysqldump\Mysqldump($dbConfig['dsn'], $dbConfig['username'], $dbConfig['password'], $dumpSettings);
            $dump->start($filename);
            echo sprintf($this->_('Database backup completed. File can be found in %s'), $filename);
        } catch (\Exception $e) {
            echo 'mysqldump-php error: ' . $e->getMessage();
        }
    }
566928
public function generate()
    {
        $result = '';

        $table  = $this->buildTable();
        $fields = $this->buildFields();

        $result.='INSERT INTO '.$table.' '.$fields;

        return $result;
    }