0

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';
                }
2
Contributors
3
Replies
19
Views
4 Years
Discussion Span
Last Post by diafol
2

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);

Edited by diafol

0

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.

1

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.