0

I have imported my website to Wordpress and facing a big issue how can I do sql Query to display data on my pages with wordpress? for example I have product, price, description which I need to display on the web site, how can I do ?

1
  • 1
    Are these in custom tables? Or are these post meta/custom fields etc? Is the data in the same database or a separate/remote database? – Tom J Nowell Feb 15 at 13:22
0

if you are trying to query from the same database in which your WordPress is installed then there is a great way to do sql query with ease. WordPress has a database access abstraction class called wpdb that allows you to run raw mysql query without any issue.

You can start using it like one of two methods bellow:

// 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );

or

// 2nd Method - Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice )
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );

Explore the documentation here and get started!

0

If it is third party DB you can first connect and then fetch results

mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");

if it is local db , you can use global wpdb object as well.

global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );

for reference. https://developer.wordpress.org/reference/classes/wpdb/

you can run the above code in functions.php.

Depending upon your requirement you can hook it with some action or add it as a shortcode.

e.g.

add_shortcode( 'dbresults', 'wp_dbresutls' );
function wp_dbresutls( ) {
 // your db code
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.