DrDog DrDog - 1 year ago 359
MySQL Question

Check if table exist using PDO

Hello all decided to begin learning PDO. However i'm having trouble creating a function to check if a table exists in my db.

Each individual item has there own table in which the table name is ($id).


$html = file_get_html('http://localhost:8888/CDOnline%20Online.html');

foreach($html->find('div.product-stamp-inner') as $content) {

$detail['itemid'] = $content->find('a',0)->href;
$detail['itemid'] = substr($detail['itemid'], 40, 6);
if (strpos($detail['itemid'], "?") !== false) {
$detail['itemid'] = substr($detail['itemid'], 0, 5);
$id = $detail['itemid'];

tableExists($dbh, $id);

function tableExists($dbh, $id)
//check if table exists

$dbh = null;

I've tried to scour the forums in search of an answer but came up empty handed. The only thing that got me close to my answer was:

function tableExists($dbh, $id)
$results = $dbh->query("SHOW TABLE LIKE `$id`");
if(count($results)>0){echo 'table exists';}

But that just says all tables exists, when half of the tables don't exist.

Edit:The table should exist if there is 1 or more rows.

Answer Source

You are using backtics around $id. Change it to single quotes. Like this:


Further note that the statement count($results)>0 will not work. You'll have to use $results->rowCount() instead.

Fxing both errors will give you the following function:

function tableExists($dbh, $id)
    $results = $dbh->query("SHOW TABLES LIKE '$id'");
    if(!$results) {
        die(print_r($dbh->errorInfo(), TRUE));
    if($results->rowCount()>0){echo 'table exists';}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download