Log in

No account? Create an account

Peter Rogers's Blog
Artist-in-Residence at Chez Firth

Friday (3/8/13) 3:01am - ... wherein Peter makes a simple db-reading plugin.

I made a simple, tiny plugin that spits out information from the WordPress database.

So I created this data in the database:

And then made a plugin that would replace this:


... with this:

Here's the plugin code:

Plugin Name: SimpleDB
Plugin URI: http://www.hujhax.com
Description: Does rudimentary database interaction within a plugin.
Version: 101
Author: Peter Rogers
Author URI: http://www.hujhax.com

if (!class_exists("SimpleDBPluginClass")) {
    class SimpleDBPluginClass {
        function SimpleDBPluginClass()
            add_action('init', array($this,'RegisterDBStyle'));
            add_action('wp_enqueue_scripts', array($this,'EnqueueDBStyle'));
            add_shortcode('SimpleDBData', array($this,'SimpleDBData'));

        function RegisterDBStyle()
            wp_register_style('dbTableStyle', plugins_url('/css/DBTableStyle.css', __FILE__), false, '1.0.0', 'all');

        function EnqueueDBStyle()

        function SimpleDBData( $atts, $content = null )
            global $wpdb;
            $myanimals = $wpdb->get_results( "SELECT * FROM test_data ORDER BY id" );

            echo <<< END_HEADER
               <div class="dbtable">

            foreach ($myanimals as $animal)
                echo "<tr><td>" . $animal->id . "</td><td>" . $animal->animal . "</td><td>" . $animal->quantity . "</td></tr>";

            echo <<< END_FOOTER

new SimpleDBPluginClass();

I also added a short css file called "DBTableStyle.css", which included these three lines:
.dbtable tr:nth-child(even) {background: #EEE}
.dbtable tr:nth-child(odd) {background: #FFF}
.dbtable tr:hover {background: #FFD}
The challenge now: how do I let visitors to the site add rows to that table?  WordPress doesn't seem to make that easy, which is perhaps a hint that they don't want blog readers doing anything like that. Another question that's occurred to me: is there any way to clean up all these HTML "echo" statements?  Instead of typing "echo '<tr>blah</tr>;", I'd much rather have a separate "View" for the HTML, or at the very least, some sort of HTMLOutputter object that would let me say "HTMLOutputter->AddTableRow('blah');", maybe guaranteeing that it gets printed out at an indentation level that makes sense.  At the moment, if I want to output clean HTML, I have to write *really* ugly PHP.

Tags: ,
Mood: [mood icon] contemplative · Music: none
Previous Entry Share Next Entry