Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding import/export functions to mysql-helper

  • Loading branch information...
commit 16600b9d1fdea66764ea9867a28f32ae3a6d7f1a 1 parent c77cd34
@mezzoblue authored
View
5 PHP/mysql-helper/includes/db/config.php
@@ -2,13 +2,18 @@
// all database configuration settings here
$config = array(
+
+ // host defines database host, plus username and password
"host" => array(
"name" => "localhost",
"user" => "root",
"password" => "root",
),
+
+ // db defines name of the database you'd like to work with, plus an optional filename for importing/exporting
"db" => array(
"name" => "testing",
+ "backupFile" => "db-backup-" . date("Y-m-d-(H-i-s)") . ".sql",
),
);
View
133 PHP/mysql-helper/includes/db/functions.php
@@ -1,5 +1,9 @@
<?
+ //
+ // DATABASE MANIPULATION
+ //
+
// create a new database
// (assumes open connection)
function createDB($connection, $db) {
@@ -9,7 +13,6 @@ function createDB($connection, $db) {
}
}
-
// drop existing database
// (assumes open connection)
function deleteDB($connection, $db) {
@@ -18,7 +21,128 @@ function deleteDB($connection, $db) {
return 'Error dropping database: ' . mysql_error();
}
}
+
+ // backup an entire db, or just a table, to a flat file
+ // (assumes open connection)
+ // (more or less copied wholesale from http://davidwalsh.name/backup-mysql-database-php)
+ function exportDB($connection, $name, $file, $tables = '*') {
+
+ // initialize
+ $return = $row2 = $result = "";
+ mysql_query('SET NAMES utf8');
+ mysql_query('SET CHARACTER SET utf8');
+ mysql_select_db($name, $connection);
+
+ // get all of the tables
+ if($tables == '*') {
+ $tables = array();
+ $result = mysql_query('SHOW TABLES');
+ while($row = mysql_fetch_row($result)) {
+ $tables[] = $row[0];
+ }
+ }
+ else {
+ $tables = is_array($tables) ? $tables : explode(',', $tables);
+ }
+
+ // cycle through
+ foreach($tables as $table) {
+ $result = mysql_query('SELECT * FROM ' . $table);
+ $num_fields = mysql_num_fields($result);
+
+ $return .= 'DROP TABLE ' . $table . ';';
+ $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
+ $return .= "\n\n" . $row2[1] . ";\n\n";
+
+ for ($i = 0; $i < $num_fields; $i++) {
+ while($row = mysql_fetch_row($result)) {
+ $return .= 'INSERT INTO ' . $table . ' VALUES(';
+ for($j = 0; $j < $num_fields; $j++) {
+ $row[$j] = addslashes($row[$j]);
+ $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
+ if (isset($row[$j])) {
+ $return .= '"' . $row[$j].'"';
+ } else {
+ $return .= '""';
+ }
+ if ($j < ($num_fields - 1)) {
+ $return .= ',';
+ }
+ }
+ $return .= ");\n";
+ }
+ }
+ $return .= "\n\n\n";
+ }
+
+ // save file
+ $handle = fopen($file , 'w+');
+ fwrite($handle, $return);
+ fclose($handle);
+ }
+
+
+ // import a flat file MySQL dump
+ // (assumes open connection)
+ function importDB($connection, $name, $file) {
+
+ // initialize
+ $returnValue = "";
+ $sql = "";
+ mysql_select_db($name, $connection);
+
+ // start reading in the file, if it exists
+ $lines = file($file);
+ foreach($lines as $line) {
+ if (strlen($line) > 1) { // to avoid blank lines
+ $sql .= ltrim(rtrim($line));
+ // if we've found a semi-colon it's time to execute
+ if (strpos($sql, ";")) {
+ if (!mysql_query($sql, $connection)) {
+ $returnValue .= mysql_error();
+ }
+ $sql = "";
+ }
+ }
+ }
+ // return any errors encountered
+ if ($returnValue) {
+ return 'Error importing database: ' . $returnValue;
+ }
+
+ }
+
+
+ // list all databases on the host
+ // (assumes open connection)
+ function listDBs($connection) {
+
+ $db_list = mysql_list_dbs($connection);
+ while ($row = mysql_fetch_object($db_list)) {
+
+ echo "<br>Database name: " . $row->Database . "<br>";
+
+ // list all rows from current database
+ mysql_select_db($row->Database);
+ $sql = "SHOW TABLES FROM " . $row->Database;
+ $result = mysql_query($sql);
+ if ($result) {
+ while ($row = mysql_fetch_row($result)) {
+ echo "Table: {$row[0]}<br>";
+ }
+ }
+
+ }
+ }
+
+
+
+
+
+ //
+ // TABLE MANIPULATION
+ //
// create a table within currently-selected database
// (assumes open connection and selected db)
@@ -111,6 +235,11 @@ function printTable($connection, $table) {
}
+
+ //
+ // HELPER FUNCTIONS
+ //
+
// trim trailing comma and remove white space from a string
// (needed to clean up SQL generated within loops)
function trimTrailingComma($str) {
@@ -119,4 +248,6 @@ function trimTrailingComma($str) {
// remove trailing comma
return (substr($str, 0, strlen($str) - 1));
}
+
+
?>
View
25 PHP/mysql-helper/includes/diagnostics/databases.php
@@ -1,25 +0,0 @@
-<?
-
- //
- // Information about the DB server
- //
- // list current databases
- $db_list = mysql_list_dbs($connection);
- while ($row = mysql_fetch_object($db_list)) {
-
- echo "<br>Database name: " . $row->Database . "<br>";
-
- // list all rows from current database
- mysql_select_db($row->Database);
- $sql = "SHOW TABLES FROM " . $row->Database;
- $result = mysql_query($sql);
- if ($result) {
- while ($row = mysql_fetch_row($result)) {
- echo "Table: {$row[0]}<br>";
- }
- }
-
- }
-
-
-?>
View
90 PHP/mysql-helper/index.php
@@ -4,13 +4,17 @@
//
// A set of simple scripts to allow database creation and schema definition through PHP
//
- // Built to work with MAMP default settings, should work on any server with proper configuration
+ // Built to work with MAMP default settings, should work on any server with proper configuration in db/config.php
//
- // Running this script will cycle between creating a database and populating then showing it,
- // or deleting it if it already exists. Not particularly useful, but it's only meant to demonstrate
- // how the various functions work.
+ // Running this script will cycle between creating a database and populating, showing,
+ // exporting, deleting, and importing it. Or simply deleting it if the database already
+ // exists. Not particularly useful, but it's only meant to demonstrate how the various
+ // functions work.
+ // for the sake of this demo
+ ob_start();
+
// database server configuration
include ("includes/db/config.php");
@@ -21,10 +25,6 @@
// common functions
include ("includes/db/functions.php");
-
- // show information about the server environment
- include("includes/diagnostics/environment.php");
-
// strict error reporting while debugging
error_reporting(E_ALL);
ini_set('display_errors', 'On');
@@ -42,9 +42,14 @@
// select this database
if (mysql_select_db($config["db"]["name"])) {
- // get some information about the database environment
- include ("includes/diagnostics/databases.php");
+ //
+ // initial setup
+ //
+
+ // get some information about the database environment
+ echo "<h2>Displaying databases</h2>";
+ listDBs($connection);
// create tables
foreach ($db_schema as $table => $keys) {
@@ -53,7 +58,6 @@
if ($tableResult) echo $tableResult;
}
-
// populate tables
foreach ($db_data as $table => $items) {
$tableResult = populateTable($connection, $table, $items);
@@ -61,8 +65,8 @@
if ($tableResult) echo $tableResult;
}
-
// display the tables on screen so we can see they were created
+ echo "<h2>Showing script-created tables</h2>";
if ($tables = getTableList($connection, $config["db"]["name"])) {
foreach ($tables as $id => $table) {
printTable($connection, $table);
@@ -70,6 +74,13 @@
}
+ //
+ // export and kill database
+ //
+
+ // dump this database to a file
+ exportDB($connection, $config["db"]["name"], $config["db"]["backupFile"]);
+
// remove the tables we just created
foreach ($db_schema as $table => $keys) {
$tableResult = deleteTable($connection, $table);
@@ -77,6 +88,37 @@
if ($tableResult) echo $tableResult;
}
+ // display the tables on screen so we can see they were dumped
+ echo "<h2>Showing tables after database export and table dump</h2>";
+ if ($tables = getTableList($connection, $config["db"]["name"])) {
+ foreach ($tables as $id => $table) {
+ printTable($connection, $table);
+ }
+ } else {
+ echo "<br><br>No tables found.<br><br>";
+ }
+
+
+
+ //
+ // import database from file and show it on screen
+ //
+
+ echo "<h2>Showing tables after file import</h2>";
+ $importResult = importDB($connection, $config["db"]["name"], $config["db"]["backupFile"]);
+ // if there's an error, show it
+ if ($importResult) echo $importResult;
+
+ // display the tables on screen so we can see they were dumped
+ if ($tables = getTableList($connection, $config["db"]["name"])) {
+ foreach ($tables as $id => $table) {
+ printTable($connection, $table);
+ }
+ } else {
+ echo "<br><br>No tables found.<br><br>";
+ }
+
+
} else {
echo "Error selecting database: " . mysql_error();
@@ -94,7 +136,27 @@
// disconnect from db server
mysql_close($connection);
-
-
+ // dump the output buffer
+ $buffer = ob_get_contents();
+ ob_end_clean();
+
+?>
+
+
+ <h1>MySQL Helper</h1>
+ <p>This script is intended as a package of basic MySQL database functions. When you load this page, it will cycle through and show one of these two alternating states:</p>
+ <ul>
+ <li>Database roundtrip: Show the existing server environment, create a new database from the contents of <code>db/schema.php</code>, populate it with example data from <code>db/data.php</code>, export it to a flat file, delete all tables, then re-import from the generated flat file.</li>
+ <li>Database dump: throwing out the previous database and showing nothing.</li>
+ </ul>
+ <p>Not particularly useful, but these functions are meant to serve more as a starting point for future code.</p>
+
+ <p>Below this line, you'll see the results:</p>
+ <hr>
+
+<?php
+
+ echo $buffer;
+
?>
Please sign in to comment.
Something went wrong with that request. Please try again.