Skip to content

3 Ways to Retrieve and show Data from the SQL Database in WordPress

mcmurryjulie / Pixabay

I just wrote this little tutorial cause I seem to always forget those methods. But they are curcial when it comes to plugin development ond plugin customization. Fortunately it isa pretty straight forward to retrieve and show data from the sql databsse in wordpress. Give it a go!

WordPress defines a class called wpdb, which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database.

Read more: http://itadminguide.com/difference-between-wpdb-get_row-get_results-get_var-and-get_query/

The $wpdb object can talk to any number of tables, but only to one database at a time; by default the WordPress database. In the rare case you need to connect to another database, you will need to instantiate your own object from the wpdb class with your own database connection information. You sometimes need to make this object global first to use it.

global $wpdb;

Use get_var() to return a single value

<?php
$customer_count = $wpdb->get_var(“SELECT COUNT(*) FROM laundry_customers;”);
echo ‘<p>Total customer: ‘ . $customer_count . ‘</p>’;
?>

Use get_row() to return a single row of data

<?php
$mycustomer = $wpdb->get_row('SELECT * FROM laundry_customers WHERE ID = 1');
echo $mycustomer -> customer_name;
?>

Use get_results() to return multiple rows of data

<?php
$allcustomers = $wpdb->get_results('SELECT customer_name, customer_id FROM laundry_customers WHERE status = 1');

foreach ($allcustomers as $singlecustomer ) {
echo '<p>' .$singlecustomer->customer_name. '</p>';
echo '<p>' .$singlecustomer->customer_id. '</p>';}
?>

Dieser Beitrag hat 0 Kommentare

Schreibe einen Kommentar

Deine E-Mail wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

An den Anfang scrollen