Populating pages from a database
-
My WP, PHP, and JS are very rusty, so I need a little assistance. My ultimate goal is to populate pages from a database. To keep it a simple example, if my site is about books and it has only two pages, one for fiction and one for non-fiction, I want those to be lists (in whatever manner I display them) to be populated from a database – separate from the default MySQL database, but hosted on the same localhost. And for this example, assume I have separate tables in my database for each page/book type –
fiction_book
andnonfiction_book
.I have put this in my themes>function.php file (after having defined the user, password, db name, and host in my wp-config.php file):
function booksdb() { global $booksdb; $booksdb = new wpdb(BOOKS_DB_USER, BOOKS_DB_PASSWORD, BOOKS_DB_NAME, BOOKS_DB_HOST); } add_action('init', 'booksdb');
And I understand I can retrieve data from the database with something like:
<?php $fictionbooks = $booksdb->get_results("SELECT * FROM $booksdb->fiction_book"); if ( $fictionbooks ) { foreach ( $fictionbooks as $fictionbook ) { do_something($fictionbook); } } else { do_something_else($fictionbook); } ?>
Having gotten that far, my initial question is: How do I confirm that I am connected to my database and am retrieving data?
Then, secondly: What is needed in
do_something
to populate the page? Or at least what is the first step I need to tackle indo_something
?Code examples I’ve seen show code of how to do things, but often don’t say what file the code should go in. And I’m not sure what code goes in WordPress files/folders and what code goes in my theme’s files/folders.
I’m not looking for a complete solution at the moment, but certainly all input is welcome. I just need a jump start. Maybe pseudo-code or the steps I’ll need to figure out the code for.
Thanks!
- The topic ‘Populating pages from a database’ is closed to new replies.