Display mysql table data in a wp page

My aim was to display data from a mysql table onto a wordpress page. I could do it using wpdb class as mentioned in the codex.But i didn’t know the file where i should write this php code that contains wpdb class functions to retrieve data from mysql table.

Hence i installed Exec-PHP plugin.(The Exec-PHP plugin executes PHP code in posts, pages and text widgets)

Now you are free to write your php code in the page editor and get the retrieved data on your page.

Steps to retrive data and display it on a wordpress page:
Create a table in mysql database(assumed that you create a table in the wordpress database itself.) In my case database_name: test, table_name:it_testtable contains 2 columns: id(number(3)) and name(varchar).
In wordpress, create a page and in the visual editor write the code(make sure you read the documentation of Exec-PHP plugin and do the required configuration mentioned,you will have to ‘disable the visual editor while writing’ option under Users section):

Here is the code to retrieve data from it_testtable and display it on this page.(wpdb class is used for wordpress database,hence you need not mention the connection parameters as wpdb already has it configured to the ‘test’ database with the username and password):

<?php

global $wpdb;
/* wpdb class should not be called directly.global $wpdb variable is an instantiation of the class already set up to talk to the WordPress database */

$result = $wpdb->get_results( “SELECT * FROM it_testtable “); /*mulitple row results can be pulled from the database with get_results function and outputs an object which is stored in $result */

//echo “<pre>”; print_r($result); echo “</pre>”;
/* If you require you may print and view the contents of $result object */

echo “ID”.” “.”Name”.”<br><br>”;
foreach($result as $row)
{

echo $row->id.” “.$row->name.”<br>”;

}
/* Print the contents of $result looping through each row returned in the result */

?>

Leave a Reply

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

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