Friday, 25 August 2017

PHP script to export table creation SQL from MySQL Database structure


The script itself is fairly self explanatory.
Note that the table name is enclosed with backticks; this prevents SQL errors if the table is named with a reserved word, which happened to me when I was writing the script.

<?php
 
set_time_limit(0);

$username = 'XXXXXX';
$password = 'YYYYYY';
$hostname = 'ZZZZZZ';
$database = 'AAAAAA';

try {
 $pdo = new PDO("mysql:host={$hostname};dbname={$database}", $username, $password);
}
catch(PDOException $e) {
 die("Could not connect to the database\n");
}

echo '<pre>';
$stmt1 = $pdo->query('SHOW TABLES', PDO::FETCH_NUM);
foreach($stmt1->fetchAll() as $row) {
 $stmt2 = $pdo->query("SHOW CREATE TABLE `$row[0]`", PDO::FETCH_ASSOC);
 $table = $stmt2->fetch();
 echo "{$table['Create Table']};\n\n";
}
echo '</pre>';
 
?> 

No comments:

Post a Comment