Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems checking whether a table exist or not in the db

Tags:

php

mysql

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

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

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 = 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";
}
like image 540
Jonathan Thurft Avatar asked Mar 24 '26 00:03

Jonathan Thurft


1 Answers

How about:

$results = $db->query('SHOW TABLES LIKE \'page\'');
if (count($results->fetchAll()) > 0) {
    echo 'table exists';
} else {
    echo "it doesnt";
}
like image 79
Scott Presnell Avatar answered Mar 25 '26 13:03

Scott Presnell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!