There are times where you would like to know if a table exists before executing an query. Most solutions require having MySQL throw an error saying “table does not exist,” but I prefer a cleaner way. I found on this forum post a clean way to do it:
/* example with table name: table_name */ SHOW TABLES LIKE 'table_name';
This solution will return 1 row if it exists, and 0 rows if it doesn’t. Here is a PHP example using this:
function DoesTableExist($name)
{
$sql = "SHOW TABLES LIKE '$name'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
return true;
}
else
{
return false;
}
}
if(DoesTableExist('users'))
{
echo "Users table found!";
}
else
{
echo "Users NOT FOUND!!!";
}
Related Posts
- MS SQL 2005 (T-SQL) Row Count for Each Table At work I needed a solution to give me a count of how many rows each table contained. I’ve always liked phpMyAdmin’s ability to list all the tables and show their size and row count. I’ve found it immensely helpful. However, I couldn’t find anything similar for SQL Server Manager...
- MySQL & PHP – SQL_CALC_FOUND_ROWS – An easy way to get the total number of rows regardless of LIMIT Here is a little trick I found awhile back. I faced a challenge several months ago where I had to query a large, complex data result from MySQL. I “paged” through the results using LIMIT and OFFSET. However, I wanted to know the total number of rows w/o the LIMIT....
- ASP .NET, LINQ, GridViews, and GUID Errors I found a simple problem today. Here is the deal, there were several times where I had to base a LinqDataSource off a Guid that I would set in the Page_Load(). I created an<asp:HiddenField /> to hold the value so all my DataSources could pull it from the control. The...
- PHP Design – Biggest Database Oversights Over the last three years I’ve had the opportunity to work on several PHP projects, some of them having grown rapidly and required to scale quickly. Three in particular have been a fantastic learning experience for me. Now I don’t consider myself a total expert, but I thought I would...
- PHP5.x or PHP6 – Argument for Type-Hinting: Better IDEs I’ve read some posting lately about PHP6, the Meeting Notes by the Developers, etc. that deal with type-hinting, especially scalar type hinting. Here is my reasoning why PHP should allow for more type-hinting scenarios: it allows IDEs to be more powerful. An example would be auto completion. Many times an...
[...] Most solutions require having MySQL throw an error saying “table does not exist,” but I prefer a cleaner way. I found on this forum post a clean way to do it:. PLAIN TEXT. Read more [...]
Great job, it definitely solved me a problem. Thanks.