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.


$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 databasen");

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']};nn";
echo '</pre>';


Developer, Technology aficionado, Beer Lover and founder of Network. Who shares a keen interest about website development, health issues, cancer awareness and other fun stuff.

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular

Most discussed