You are here

function _demo_dump_table_data in Demonstration site (Sandbox / Snapshot) 5

Same name and namespace in other branches
  1. 8 demo.module \_demo_dump_table_data()
  2. 6 database_mysql_dump.inc \_demo_dump_table_data()
  3. 7 database_mysql_dump.inc \_demo_dump_table_data()

Dump table data.

This code has largely been stolen from the phpMyAdmin project.

1 call to _demo_dump_table_data()
demo_dump_db in ./database_mysql_dump.inc
Dump active database.

File

./database_mysql_dump.inc, line 77

Code

function _demo_dump_table_data($table) {
  $output = "\n";
  $output .= "--\n";
  $output .= "-- Dumping data for table '{$table}'\n";
  $output .= "--\n\n";

  // Dump table data
  $result = db_query("SELECT * FROM %s", $table);

  // 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 = array(
      '\\',
      "'",
      "\0",
      "\n",
      "\r",
      "\32",
    );
    $replace = array(
      '\\\\',
      "''",
      '\\0',
      '\\n',
      '\\r',
      '\\Z',
    );
    $insert_cmd = "INSERT INTO `{$table}` VALUES\n";
    $insert_buffer = '';
    $current_row = 0;
    $query_size = 0;
    while ($row = db_fetch_array($result)) {
      $current_row++;
      $values = array();
      $field = 0;
      foreach ($row as $value) {

        // NULL
        if (!isset($value) || is_null($value)) {
          $values[] = 'NULL';
        }
        else {
          if ($fields[$field]->numeric && !$fields[$field]->timestamp && !$fields[$field]->blob) {
            $values[] = $value;
          }
          else {
            if ($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) . ')';
        if ($query_size + strlen($insert_buffer) > 50000) {
          $output .= ";\n";
          $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";
  }
  return $output;
}