admin管理员组

文章数量:1122832

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 ?

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 ?

Share Improve this question edited Feb 15, 2021 at 15:24 claire_ 555 bronze badges asked Feb 15, 2021 at 13:05 MartinMartin 11 bronze badge 1
  • 2 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 Commented Feb 15, 2021 at 13:22
Add a comment  | 

2 Answers 2

Reset to default 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!

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
 }

本文标签: queryDisplay data from phpMyAdmin with WordPress