Forum Moderators: open

Message Too Old, No Replies

Using PHP to see if tables with the "example" prefix exist?

PHP MySql

         

jncr

12:26 am on Nov 28, 2007 (gmt 0)

10+ Year Member



Hi, I need to know how to use PHP to check if a table with the "example" prefix exists. Thanks for any help.

~JNCR

ZydoSEO

6:32 pm on Nov 28, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The code below should give you an idea... It lists all of the tables for a particular DB name...

I would think you could simply add " LIKE 'somepattern'" to the SHOW TABLES command (SHOW TABLES FROM mydb LIKE 'somepattern') where somepattern is something like 'EXAMPLE%' or 'EXAMPLE*' (not sure what the wildcard character is in MySQL - '%', '*', or other).

Put it in a function and return true/false depending on whether you get rows back from the SHOW TABLES command.

*****************************************

<?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?>