function _demo_dump_table_data in Demonstration site (Sandbox / Snapshot) 8
Same name and namespace in other branches
- 5 database_mysql_dump.inc \_demo_dump_table_data()
- 6 database_mysql_dump.inc \_demo_dump_table_data()
- 7 database_mysql_dump.inc \_demo_dump_table_data()
Dump table data.
This code has largely been stolen from the phpMyAdmin project.
Parameters
$fp: The file handle of the output file.
$table: A table name to export the data for.
1 call to _demo_dump_table_data()
- demo_dump_db in ./
demo.module - Dump active database.
File
- ./
demo.module, line 327
Code
function _demo_dump_table_data($fp, $table) {
$output = "\n";
$output .= "--\n";
$output .= "-- Dumping data for table '{$table}'\n";
$output .= "--\n\n";
// Dump table data.
$result = \Drupal::database()
->query("SELECT * FROM `{$table}`", [], [
'fetch' => PDO::FETCH_ASSOC,
]);
// Get table fields.
if ($fields = _demo_get_fields($result)) {
// Disable indices to speed up import.
$output .= "/*!40000 ALTER TABLE {$table} DISABLE KEYS */;\n";
// Escape backslashes, PHP code, special chars.
$search = [
'\\',
"'",
"\0",
"\n",
"\r",
"\32",
];
$replace = [
'\\\\',
"''",
'\\0',
'\\n',
'\\r',
'\\Z',
];
$insert_cmd = "INSERT INTO `{$table}` VALUES\n";
$insert_buffer = '';
$current_row = 0;
$query_size = 0;
foreach ($result as $row) {
$current_row++;
$values = [];
$field = 0;
foreach ($row as $value) {
// NULL.
if (!isset($value) || is_null($value)) {
$values[] = 'NULL';
}
elseif ($fields[$field]->numeric && !$fields[$field]->timestamp && !$fields[$field]->blob) {
$values[] = $value;
}
elseif ($fields[$field]->binary && $fields[$field]->blob) {
// Empty blobs need to be different, but '0' is also empty :-(.
if (empty($value) && $value != '0') {
$values[] = "''";
}
else {
$values[] = '0x' . bin2hex($value);
}
}
else {
$values[] = "'" . str_replace($search, $replace, $value) . "'";
}
$field++;
}
if ($current_row == 1) {
$insert_buffer = $insert_cmd . '(' . implode(', ', $values) . ')';
}
else {
$insert_buffer = '(' . implode(', ', $values) . ')';
// Check if buffer size exceeds 50KB.
if ($query_size + strlen($insert_buffer) > 50000) {
// Flush to disc and start new buffer.
fwrite($fp, $output . ";\n");
$output = '';
$current_row = 1;
$query_size = 0;
$insert_buffer = $insert_cmd . $insert_buffer;
}
}
$query_size += strlen($insert_buffer);
$output .= ($current_row == 1 ? '' : ",\n") . $insert_buffer;
}
if ($current_row > 0) {
$output .= ";\n";
}
// Enable indices again.
$output .= "/*!40000 ALTER TABLE {$table} ENABLE KEYS */;\n";
}
fwrite($fp, $output);
}