Wordpress & Web Development

Working With Custom Database Tables In WordPress

James Bruce 15-02-2012

custom database tableI’ve shown you many ways in which WordPress is already the most flexible CMS 5 Things You Might Not Have Known You Could Do With Wordpress Being the most versatile blogging system ever, it’s no surprise that developers have twisted and pulled Wordpress into becoming so much more through the clever use of plugins. If you thought Wordpress was only for... Read More . A quick scan of the Best of WordPress Plugins The Best WordPress Plugins Read More page will also reveal some of the many unique and niche ways you can make your blog work harder. I’ve even shown you how to make use of custom post types How to Make Your Own Events Listing Using Custom Post Types in WordPress WordPress allows you to use Custom Post Types to extend built-in functionality. Here's how to do it without plugins. Read More to create your own mini database Make A Product Review Database With Wordpress: Custom Post Types, Custom Fields, Featured Images & Widgets! Last time we showed you how to create a simple events listing using perhaps the most powerful feature of WordPress 3.0 - custom post types. After some requests to develop this further, today we’ll be... Read More ; but I’ve left one thing out, I think.


What if you already have a database of say, customer information, but you want to be able to query that data and display it within a WordPress template? Today I’ll be showing you just how to do that, safely within the WordPress engine.


This tutorial is about as advanced as we are going to get at MakeUseOf, but it should open up a world of possibilities to you.

Why Would I Do This?

Despite the many plugins and extensions available to us in WordPress, sometimes you already have a dataset and migrating it to a format WordPress likes would be more hassle than it’s worth – especially if you then have another system you need to interoperate with.

Today, I’ll be taking the example of a simple customer information database, and we’ll be creating a page template that lists these customers – only to registered WordPress users (though the page itself will be accessible from the front end of the site).

As a reference for column and table names in the database, you might find it helpful to install the Database Browser plugin, which will also let you run basic where and order by queries to test your SQL code. Here’s a screenshot with a sample dataset I’ve created – in this case, a table called Customers, containing some basic information about each of my very important clients.


custom database table

What Precisely Are We Going to Do Here?

  • Creating a new page template which we can then apply some custom PHP code to.
  • Looking at how to create a custom query to the database, and then parse the results – using built-in WordPress database classes.
  • Looking at permissions in case you want to restrict access.

Making a Custom Template

If you want to use some of your own PHP code, the easiest way to do this is to create a custom template, then apply the template to a particular page you create in WordPress. Start by opening up your theme files and duplicating the page.php (or single.php if there isn’t one). Rename it something obvious, like “template-customers.php” as I’ve chosen.

At the very top of the file, we need to tell WordPress this is a custom template. Do this by adding the following (this is a PHP style comment, so it should be after any opening PHP tag if present):

Template Name: Customers

Obviously, call it whatever you like.


Now, find the main content function. You can delete it if you want, but I’m just going add the extra code after it. With the default twenty-eleven theme, you’re looking for:

<?php get_template_part( 'content', 'page' ); ?>

But in most themes, it’ll be something like:

<?php the_content();?>

That’s the bit that displays your post content, so anything you add after that will be shown just after the main content area. Just to check it’s all working, let’s add a basic echo statement and save the file.

<?php echo "This is our custom template!";?>

Before we can check this, we’ll need to create a page on the WordPress admin page, and apply our page template to it.


custom database table wordpress

Publish, and check out the page to see if your echo statement has worked.

custom database table wordpress

The Custom Query Class

To gain direct access to the database, all you need to do is use the $wpdb object by making it global. These three lines should do it – replace the generic echo statement we made earlier with this:

global $wpdb;
$customers = $wpdb->get_results("SELECT * FROM customers;");

Save, and refresh the page. The print_r() function just dumps out all the data from the customer’s object – so you should see that your simple SQL statement to select everything from the customer table has worked nicely. Now all you need to do is parse the results to something useable. Of course, you can put any SQL select statement into the get_results() method, but I’m not here to teach you SQL so we’ll stick with just grabbing everything for now.

To parse the results out into something more meaningful, I’ll just be using a basic table for now. Replace the print_r method with the following code (don’t worry, I’ll be pasting the full code later on if you don’t want piece it together yourself):

echo "<table>";
foreach($customers as $customer){
echo "<tr>";
echo "<td>".$customer->name."</td>";
echo "<td>".$customer->email."</td>";
echo "<td>".$customer->phone."</td>";
echo "<td>".$customer->address."</td>";
echo "</tr>";
echo "</table>";

Once you have each customer object inside a foreach, you can access the field names easily with $customer->field_name – it really couldn’t be simpler.

Securing Things

In this instance, I don’t really want my customer data displayed to just anyone and indexed by the search engines – but I do still want it on the front end displayed using this template; so what can we do? Easy, we’re going to make use of the WordPress conditional is_user_logged_in(), and display a quick message if they aren’t. Here’s the whole block of code again with the new conditional added:


if (is_user_logged_in()):

global $wpdb;
$customers = $wpdb->get_results("SELECT * FROM customers;");

echo "<table>";
foreach($customers as $customer){
echo "<tr>";
echo "<td>".$customer->name."</td>";
echo "<td>".$customer->email."</td>";
echo "<td>".$customer->phone."</td>";
echo "<td>".$customer->address."</td>";
echo "</tr>";
echo "</table>";
echo "Sorry, only registered users can view this information";


Save and refresh, and you should still see the content. However, log out, then refresh the page, and you’ll now see the “Sorry, only registered users…” message.

custom database table

If you wanted to restrict this to certain levels of users rather than all registered users, then you would use the current_user_can() conditional instead, along with an associated capability (read more about capabilities on the codex). This would check for admin users, for example – the only users who can manage plugin options:

current_user_can( 'manage_options' )


I’m going to leave it there today as anything else would become an SQL tutorial or how to style your output with CSS. The sky really is the limit with WordPress, and I hope this comes in useful to some of you in your WordPress projects.

Next week I’ll be tackling the slightly trickier topic of how to insert data back into your custom database using a form on the page, and a bit of AJAX/jQuery magic. And take a look at some of our other WordPress guides, like solving 500 internal server errors and blank pages The Ultimate Guide to Solving 500 Internal Server Errors and Blank White Pages in WordPress Having trouble with 500 Internal Server Errors and blank pages in WordPress? Here's how to fix them right away. Read More  and featured thumbnail and image sizes The Complete Guide to Featured Thumbnails and Image Sizes in WordPress Here's everything you need to know about image sizes in WordPress and managing featured images. Read More .

Don’t have a WordPress installation yet? Check out our guide to installing WordPress on Bluehost How to Install WordPress on Bluehost Bluehost is among the largest, most popular web hosting providers. Here's an easy guide on how to install WordPress on Bluehost. Read More .

Related topics: Webmaster Tools, Wordpress Plugins.

Affiliate Disclosure: By buying the products we recommend, you help keep the site alive. Read more.

Whatsapp Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. MiM
    November 10, 2019 at 9:45 am

    awesome! best tutorial for read data from database and display on wordpress template page. TNX

  2. WildOnion
    June 23, 2017 at 12:38 pm

    I am working in a multisite environment. Would the above instructions about still apply for me, and what are the potential problems I might have with the other websites if I modify the PHP files?

    • James Bruce
      June 23, 2017 at 12:50 pm

      In theory, yes. Each site has it's own theme files, so modifying your own PHP theme files is not an issue. However, working directly with the database would be quite risky if there are lots of other sites, and if you're not the admin anyway, you wouldn't be allowed to touch the DB like this.

  3. sudhansu
    May 19, 2017 at 11:34 am

    Merging table cells in rows with the same name into one cell in wordpress

    Name Description Product Action
    name1 description here product 1 edit delete
    name1 description here product 2 edit delete

    I want to result like this

    Name Description Product Action
    name1 description here product 1 edit delete
    product 2

    Please help me to solve the problem.

  4. Liry
    May 13, 2017 at 1:33 am

    Hi, sometimes I get a 500 server error when I view this webpage. I thought you may wish to know, cheers

  5. Kiran Gole
    April 15, 2017 at 8:44 am

    Hello James,

    This has been a fantastic step by step article for beginners to display custom data tables and I really enjoyed working out each step to obtain the base desired results. I was wondering on this for quite a long time on how to display the table contents and was unable to execute it the right way. Yes I am not a developer by genes and hardly understand the coding per say (being an IT Infrastructure person) but this document gave me a light path to follow.

    My next search is to formulate the displayed table (with some advance search in front end) on the page displayed but not much with coding though :) Lets see !!

    This is a small note of my appreciation.

    Thanks a ton :)

  6. Gautam Bose
    February 8, 2017 at 5:15 am


    I have a long table.How to paginate his.

  7. Gautam Bose
    February 7, 2017 at 8:42 pm

    How to use Custom css and javascript in custom template?

  8. Nathan Simpson
    December 12, 2016 at 8:52 pm

    Awesome article! Super helpful. Thanks very much. I made my first custom plugin using this article almost exclusively!

  9. HikingMike
    November 5, 2016 at 2:17 am

    Hi James, fantastic article. I have a question. Since you have a custom page template, that probably means that you don't have a way to use this method to access data on a page or post or something that is independent of the theme, right? If you change the theme, you'll have to make a new custom template for that theme. So is there is a way to do it that will work fine even if you change the theme?

    I thought of having just a PHP include that would do the work and I could include it in a custom template file so there is slightly less work in theme change, but still not great.

    I know you've mentioned custom post types in the comments. Could that work somehow for this? I read your next post about AJAX/form submission/SQL INSERT as well, but I see modifications to the theme file functions.php there.

    Or perhaps a plugin would be only way to do it?


  10. Varon
    May 22, 2016 at 6:35 am

    Hi, i tried this tutorial and its great but it is not displaying any values, if i use the "ïf use logged in" and i run page while logged out, it displays that i have to be logged in, but its not displaying results. please help

    • Varon
      May 22, 2016 at 6:40 am

      oh sorry forgot to add that if i use the print_r statement, it displays all info.

  11. rob
    April 28, 2016 at 8:01 pm

    great info here! Would it possible to extend what you've done here to create a dynamic page for each customer to display their information?

    Something like [Broken Link Removed] which shows the corresponding customer's profile information?


    • Parteek
      October 11, 2016 at 8:26 pm

      did you get a solution for this problem ?

  12. Anonymous
    April 8, 2016 at 2:36 pm

    Hi, great tutorial but could you please advise if there is any way to pass parameters to the SQL select statement please?

    Using your example of a Customer List, could we, for instance, have a dropbox box list of names or address (towns) and then only select records from the DB matching that criteria?

    • James Bruce
      April 8, 2016 at 3:57 pm

      Assuming you've already populated the drop down, then of course, just parse the form data with PHP and plug those variables into the select statement. Something like:

      $customers = $wpdb->get_results("SELECT * FROM customers WHERE name = ".$_POST['name'].";");

      • Anonymous
        April 11, 2016 at 10:30 pm

        Thanks James.
        I really am a learner here. Any good examples of this you could point me to please?
        ("Parse the form data with PHP"?)

        Thanks again!

  13. Sokhawin
    March 22, 2016 at 10:35 pm

    Great sharing

  14. Nearly Pulled Out All My Hair
    March 1, 2016 at 7:41 pm

    So well written and helpful!
    THANK YOU doesn't cover it...
    If I had a huge box of fresh cookies I'd hand 'em over to you right now.
    No joke.

  15. lubosh7
    January 27, 2016 at 3:53 pm

    Excellent post. It works. Just what I needed. Thank you.

  16. Leonidas Brasileiro
    December 1, 2015 at 8:06 pm

    Very good! Concise and fun. Helped me a lot. Thanks.

  17. Anonymous
    October 10, 2015 at 7:58 pm


    For some reason the print function works as expected, but when I use the echo & foreach statements it causes the page to be blank. Any idea what could cause that?

    • James Bruce
      October 11, 2015 at 7:25 am

      probably just an error in your code. Make sure youve enabled debug mode by changing the line in wp-config about wp_debug from false to true. Post back with the error and code if you don't know how to fix it.

    • Davor
      December 30, 2015 at 1:03 pm

      You need to add array number when echoing, example:

      echo $element[0]->title;

  18. Anonymous
    July 15, 2015 at 4:11 am

    This is not in the wordpress codex docs and really should be. Thanks for writing!

  19. shilpi
    May 2, 2015 at 1:48 pm

    This is just fantastic.... I was desperately searching for this... Thanks... thank you very much

  20. SimbaLion
    April 28, 2015 at 7:39 pm

    Hi I tried following this with some minor adjustments but it is not working. Here is what I've got:

    get_results("SELECT * from business where id=1;");print_r($business);
    name; ?>

    the print_r function works and prints out the whole array, but the echo function displays nothing. What am I doing wrong? :(

  21. Dan
    April 25, 2015 at 5:40 am

    Thanks man. This helped a lot and was exactly what I needed.

  22. Kossi
    February 18, 2015 at 3:10 am

    Hey James,
    Would please tackle the topic of how to insert data back into your custom database using a form on the page, using AJAX/jQuery as you have mentioned it earlier? That will be much appreciated.
    Thank you James

  23. Kossi
    February 18, 2015 at 3:01 am

    Awesome work man! You really nailed this tutorial down.

  24. Jota Rodriguez
    February 12, 2015 at 3:16 pm

    Hi , congratulations on your article . My project is to create a database with customer trasancciones . In his private area, each customer will see only the data of your transactions.

    I followed your tutorial but nothing is displayed on the page I created.

    What could be the problem ?
    Greetings from Madrid.

  25. Matthew Sokanovic
    January 26, 2015 at 7:28 pm

    Hi there all!

    I am wondering if anyone can help me. For a start this is ideal for me but I need to use a form to add an entry to a database. Is it as simple as using this and then leaving the action blank to make it submit to the same page? I can put together the php to write to the database ect. It's just most the solutions I have tried and simply taken me to a 404 error page after I submit the form.

    Anyway any help would be appreciated massivley!

  26. Asad
    January 14, 2015 at 8:07 pm

    First Of all Thank you for the awesome tutorials :)
    My project was to create a form ,store its data to database and get the data on front page so i just did it.
    but i want it like wordpress posts. Mean to say when custom row id is click i want to open the content in single page how can i do that.
    i think it is not impossible although difficult

    • James Bruce
      January 15, 2015 at 8:15 am

      Two ways. You can either make your new content as a new custom post_type, which would give ti the same structure as any other wordpress post. Or you could direct all clicks to a single page which acts as the handler - pass in the item ID as a parameter on the link, and then that page fetches the relevant post. That would give you a single URL for SEO purposes, which has dynamic content depeneding on parameter. If you want Google to index this content, you will need to work within WordPress cusotm post types.

  27. RCU
    January 13, 2015 at 8:18 pm

    Thanks for an amazing article!!!
    How can I display info from the database as a checkbox with wpdb?
    Thanks again!!

  28. scott
    December 19, 2014 at 7:15 am

    The template i made is not showing on the add page of admin panel.
    i dont know why this problem is occurring????

  29. Heidi
    July 12, 2012 at 2:57 pm

    Great article.
    You mentioned that you would post the full code. I can't find where that is.
    Perhaps a good follow up post would be creating a page with a form to add information to that table.

    • James Bruce
      July 12, 2012 at 3:20 pm

      Hi Heidi, glad you appreciate it. The full code block is the one just under the subtitle "securing things".

      This method of working with the database is only really recommended if you already have something external that you've used to import or deal with the data. If you'd like to add information to the db from within wordpress, I'd suggest you then make those datatypes into custom posts - see the tutorial here: //www.makeuseof.com/tag/events-listing-custom-post-types-wordpress/ - that'll give you a form in the admin section to add new items.

  30. Fabio
    June 28, 2012 at 12:01 am

    excellent tutorial, men!..

  31. Tom
    June 25, 2012 at 2:05 pm

    Hi there,
    I followed your tutorial and it works! I used your tutorial to display a list of events.
    My question: How can I get detailpages. Regarding to your example, I have a list of customers, but how can I make detailpages for each customer?
    Including fancy urls like
    Do you have a tutorial for that?

    • muotechguy
      June 25, 2012 at 3:35 pm

      Hi Tom; if you want to start integrating it into the core WordPress functionality like you're describing with permalinks, you're better off making the data as a custom post type, not a custom database table. See my tutorial here: //www.makeuseof.com/tag/events-listing-custom-post-types-wordpress/

      • Tom
        June 27, 2012 at 10:45 am

        custom post types is not an option. In my event-database there are several options that take a lot of (re)programming. So I prefer working with my own database.

        Any suggestions to create detailpages?

        • muotechguy
          June 27, 2012 at 10:49 am

          I'm not how you would the exact format you specified, but you could pass the customer as a request variable in the url to the customers page, with a custom template.

          so, domain.com/customers?name=whatever would find the name variable and display a detail page instead?

          This wouldn't be indexable though, I think.

  32. hassan
    June 25, 2012 at 12:13 pm

    Hello everyone, please tell how can i access database of WordPress(make new tables and get data from tables)through android application please share any code example if any body have.

  33. Igor
    June 24, 2012 at 5:08 pm

    Could you please tell me how did you get your "custormers" table into wordpress database so that it became visible on Database Browser. I added new table inside wordpress database but it wasnt populated on the Database Browser drop down menu

    • muotechguy
      June 24, 2012 at 5:13 pm

      Double via phpmyadmin; how can you be sure you added the table?

      • Igor
        June 24, 2012 at 5:28 pm

        I added it from Cpanel in phpadmin

        • muotechguy
          June 24, 2012 at 8:21 pm

          You're sure its actually a table in the same database wordpress uses? Maybe you accidentally created a new database. Theres no reason for it not be visible.

  34. Randy
    June 15, 2012 at 6:44 pm

    Wow.... some pretty ungrateful comments. This is a great tutorial. Very useful for those with a little more MySQL knowledge than WP knowledge.

    I'd be curious as to how you could use the wp_search() function to perhaps search that separate MySQL table as well, if at all possible, rather than using LIKE in a MySQL query.

    Great tut.

    • muotechguy
      June 16, 2012 at 8:56 am

      Thanks Randy. If we assume that modifying core WP code is a no-go, I dont think this would be possible. Presumably, you'd want the information separate somehow though, so my approach would probably be to modify the search results page, intercept the search term, and display an additional set of result using a custom query.

  35. Bill Woodland
    June 3, 2012 at 4:11 pm

    If you create your own tables in the WP database, does the WP tools/export back it up for you, or do you have to write your own backup routine for your own tables?

    • muotechguy
      June 12, 2012 at 8:34 pm

      The export tool only extracts specific data and stores it as XML file, so I don't believe it would back up custom tables. Other plugins would though, as well as obviously any regular SQL export.

  36. James Bruce
    February 23, 2012 at 12:16 pm

    Marlan, why don't you think this would be appropriate for WP? As long as you have caching enabled, it should handle this fine. I've made similar (scraper) sites in the past, and those were done either with regular posts on another wp install, or using custom post types. WordPress is more than capable of handling huge numbers of entries - makeuseof currently has 12,000 articles on the main site with 100,000 or so comments, and that serves millions of impressions a day. 

    • Marlan
      February 23, 2012 at 5:17 pm

      James - You may have a point. 

      I had found an awful lot of articles which led me to believe just putting an extra table in the wp database and then using a page and a little plugin would be easy and perform well. And it was true - in about a day I had my database up online. But now I see that making the comment system work with the database is trickier than I thought - not impossible - but tricky. Not a lot of literature out there on how to add comment filters and I can't tell if I can filter comments on meta-data... so I have lots of questions on that.I currently have about 200 pages in my "pages" part of WP. But I'm finding having lots of pages is a pain to go through when trying to find and update. But maybe you are right and I should bring everything into the pages methodology. My data doesn't change much and cacheing would work just fine. Then I just get real comfortable with using the admin search to get to my pages.What do do what to do? That is always the question. 

  37. Narenjinews
    February 16, 2012 at 11:17 am

    Why have you focused on WordPress. Put something about Blogger.

    • James Bruce
      February 16, 2012 at 1:06 pm

      Blogger is a free blogging platform that gives zero access to the database. WordPress is a self installed PHP application to run on your own server. You will never be able to do anything with blogger beyond blogging. ...