I want to check table exists from my defined array. It return result but when i delete any table from database it still say ok. I want exactly have to be match from my array value and database tables name. so how can i improve???? plz help.
include 'connect.php';

function db_table_exists($table_array){
                    foreach ($table_array as $db_table) {
                        $check = mysql_query("SELECT * FROM `{$db_table}`");

                        if($check !== false){
                            return true;
                        }else{
                            return false;
                        }
                    }
                }

                define('USERS', 'users');
                define('COMMENTS', 'test');
                $tables =   array(USERS, COMMENTS);
                if(db_table_exists($tables) == true){
                    echo 'ok';
                }else{
                    echo 'prob';
                }

Recommended Answers

All 3 Replies

Member Avatar for diafol

To get a list of the tables in the mysql DB...

function exisitingTables()
{
    $result = mysql_query("SHOW TABLES");
    $tables = array();

    if(mysql_num_rows($result))
    {
        while($data = mysql_fetch_array($result, MYSQL_NUM))
        {
            $tables[] = $data[0];
        }
    }

    return $tables;
}

Use it by...

$tables = existingTables();

for example

You can then run something like...

$checkTable = "users";

$res = in_array($checkTable,$tables);

Thanks for helping me DIAFOL. But in the $checkTable variable can i use array?
If i can how can i do. I thik it will be less my code. Cause If i have 100 of tables, I have to use 100 time this function. If u can plz share something.

Member Avatar for diafol

Sure you can use an intersect to get all the matches...

$checktables = array("thistable","thattable","histable","hertable", "mytable");
$result = array_intersect($checktables, $tables);

The $result will hold all matches - so it will be an array - empty or otherwise.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.