3

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";
}
1
  • 1
    This won't help you with your question, but can you please choose a consistent quotation style? You use " and ' very haphazardly. Pick one or the other and use it throughout your code. Commented Aug 23, 2012 at 18:38

2 Answers 2

3

How about:

$results = $db->query('SHOW TABLES LIKE \'page\'');
if (count($results->fetchAll()) > 0) {
    echo 'table exists';
} else {
    echo "it doesnt";
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works. Thank you. I still dont know why it doesnt work the previous one tho... is pretty much the same
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.