Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a MySQL database is empty using PHP

Once a database is created how can it be checked if the database contains tables or table structure using PHP?

Scenario:

When the user accesses the system first time it creates a default database with no tables, then in the next step the user is supposed to import the customized database structure by uploading .sql file. I need to check if they have imported the database or has skipped that step by checking if the default database that was automatically created earlier has any table structure.

When I executed mysql_list_tables(defaultDBName) it just returns "Your SQL query has been executed successfully", but no result set in phpMyAdmin.

like image 781
Rav Avatar asked Oct 26 '25 12:10

Rav


1 Answers

<?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    echo 'Could not connect to mysql';
    exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
    echo "DB Error, could not list tables\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?>

from Documentation http://php.net/manual/en/function.mysql-list-tables.php

You can use if(mysql_num_rows($result) > 0) instead of looping through $result..

like image 142
Rajat Singhal Avatar answered Oct 28 '25 01:10

Rajat Singhal