PaulJ
PaulJ

Reputation: 1

Wordpress How to retrieve results from database using $wpdb

I have a table of values and I would like a user to choose a row from the list with a drop-down menu in a WordPress page and have values from various columns populated in the same WordPress page.

I am trying to learn how to use the $wpdb class in WordPress to do this, I am trying to understand first how to write something that will be displayed in the user's browser, but I think I might be missing some critical parts:

What I have done is to create a table called 'wp_axleaa' in my WordPress database. I am trying to query this table and the only result I get printed is “Array”

I wrote a plugin as follows:

<?php
/**
* @package Trying to Connect
* @version 1.6
*/
/*
Plugin Name: Trying to Connect
Plugin URI:
Description: Connecting to DB with $wpdb
Author: Paul J
Version: 1.0
Author URI:
*/

function tc_info() {
    global $display;
    global $wpdb;
    $display = $wpdb->get_results(
    '
    SELECT *
        FROM $wpdb->wp_axleaa
    ');
    print $display;
    }

add_shortcode('showinfo','tc_info');
?> 

Then I put the shortcode [showinfo] into my WordPress site, and when I view the page then it just shows “Array”. If I add a WHERE clause to the SQL statement, then I get an error message on the page.

I am very new to WordPress and writing PHP and would really appreciate any help, I'm sorry if this is a long-winded question...

Thanks very much,

Upvotes: 0

Views: 11790

Answers (2)

CarlosOnWeb
CarlosOnWeb

Reputation: 11

That's because get_results() returns an array. You may want to modify your code like this:

function tc_info() 
{
    global $wpdb;
    $output = '';

    $sql = 'SELECT * FROM $wpdb->wp_axleaa';

    $rows = $wpdb->get_results( $sql );

    if ( $rows ) {
       foreach ( $rows as $row ){
     $output .= $row[0];
       }
    }
    print $output;  
 }

Upvotes: 1

brasofilo
brasofilo

Reputation: 26075

Your problem is not exactly retrieving the database info. First, Shortcode values should be returned. Not printed or echoed. Second, you need to do something with the array you're receiving from the DB query.

To have a nicely formatted display of the array contents, instead of print $display;, use:

return '<pre>' . print_r( $display, true ) . '<pre>';

If you want fast progress in learning, you'll need to consult the documentation frequently:

Upvotes: 0

Related Questions