检查数据库中是否存在表的问题

时间:2022-09-26 07:42:31

Basically I have my MySQL dbname = test and my table name = page.

基本上,我有MySQL dbname = test和表名= page。

I want to create a query using a php PDO to check if the table "page" exists in my db "test"

我想使用php PDO创建一个查询来检查表“页面”是否存在于我的db“测试”中

I've tried these 2 things but it doenst work.. the first example always tells me that it doesn't exists.. even when it does exists in my db and the 2nd example tells me that it always exists... even when it doesnt exists....

我试过这两种方法,但都没用。第一个例子总是告诉我它不存在。即使它确实存在于我的db中,第二个例子告诉我它总是存在……即使它并不存在....

$db = new PDO('mysql:host=' . $DB_SERVER . ';dbname=' . $DB_NAME, $DB_USER, $DB_PASS);

if (array_search('pages', $db->query('show tables')->fetch()) !== false) {
    echo "the db exists";
} else {
    echo "the db doesnt exists";
}

I've also tried this

我也试过这样

$results = $db->query('SHOW TABLE LIKE \'page\'');
if (count($results) > 0) {
    echo 'table exists';
} else {
    echo "it doesnt";
}

2 个解决方案

#1


3  

How about:

如何:

$results = $db->query('SHOW TABLES LIKE \'page\'');
if (count($results->fetchAll()) > 0) {
    echo 'table exists';
} else {
    echo "it doesnt";
}

#2


0  

Make sure your user has access to the information schema database, and do:

确保您的用户能够访问信息模式数据库,并做到:

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'database_to_search'
AND TABLE_NAME LIKE "table_here%" 

Then grab and check your results. Using the above, if you needed to, allows you to also limit your response (offset, limit).

然后获取并检查结果。如果需要,可以使用上面的方法来限制响应(偏移量、限制)。

#1


3  

How about:

如何:

$results = $db->query('SHOW TABLES LIKE \'page\'');
if (count($results->fetchAll()) > 0) {
    echo 'table exists';
} else {
    echo "it doesnt";
}

#2


0  

Make sure your user has access to the information schema database, and do:

确保您的用户能够访问信息模式数据库,并做到:

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'database_to_search'
AND TABLE_NAME LIKE "table_here%" 

Then grab and check your results. Using the above, if you needed to, allows you to also limit your response (offset, limit).

然后获取并检查结果。如果需要,可以使用上面的方法来限制响应(偏移量、限制)。