Check if Table or Column already exists in Database?


While working on web development, we all come on a situation where we need to check if table(s) exists on database. This mainly arise during backend development. You will encounter this situation frequently when you are working on WordPress Theme Development or Plugin Development.

In this short tutorial, we will be checking if the table already exists on the database on WordPress. This will be a tip more than a tutorial. So, let’s get started.

Let’s explain our code above. We are testing this code in WordPress. I hope you are already familiar with $wpdb object. This is used to interact with a database without needing to use raw SQL statements. By default, WordPress uses this class to instantiate the global $wpdb object, providing access to the WordPress database.

The actual line that checks if table already exists or not is inside if statement.

$wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name

This statement return true if there is no table with the name $table_name and vice versa.

Now, let’s move on to our second part. We can check if a certain column exists on the table. We will use $wpdb object for the function as well. We will create a new function to check the condition. If column exists, return true else false.

Here, the %s is replaced by the variable passed by the end of its statement. For example, the first %s is replaced by Database Name, second by $table_name and last one by $column_name.

Read More Articles



Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.