1

How can I access to my WordPress database and run SQL from the widget code? (I need to access to the settings of one of my plugins from the widget code)

1
  • Maybe you don't need the SQL query. What's the goal? Can you post the relevant code? Commented Jun 28, 2013 at 22:02

3 Answers 3

3

If you want to retrieve some information from the database, you can use one of four helper functions to query the database and retrieve the data.

get_results():

This is the function that we looked at earlier. It is best for when you need two-dimensional data (multiple rows and columns). It converts the data into an array that contains separate objects for each row.

get_row():

When you need to find only one particular row in the database (for example, the post with the most comments), you can use get_row(). It pulls the data into a one-dimensional object.

get_col():

This method is much the same as get_row(), but instead of grabbing a single row of results, it gets a single column. This is helpful if you would like to retrieve the IDs of only the top 10 most commented posts. Like get_row(), it stores your results in a one-dimensional object.

get_var():

In many cases, you will need only one value from the database; for example, the email address of one of your users. In this case, you can use get_var to retrieve it as a simple value. The value’s data type will be the same as its type in the database

An example:

<?php
$drafts = $wpdb->get_results("SELECT ID, post_title FROM wp_posts WHERE post_status = 'draft' AND post_author = 5");
foreach ( $drafts as $draft ){
    echo $draft->post_title;
}
?>

Documentation: http://codex.wordpress.org/Class_Reference/wpdb

Source: http://wp.smashingmagazine.com/?p=98071

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

FROM $wpdb->posts should probably be FROM wp_posts ? Here is a WP DB diagram I found: codex.wordpress.org/Database_Description. It might help someone one day... :)
2

You can check this http://codex.wordpress.org/Class_Reference/wpdb for full documentation. In resume you can do something like the follow from any part of your widget code:

global $wpdb;
$rows = $wpdb->get_results( "SELECT id, name FROM table" );

Comments

2

just include wp-blog-header.php in the file

require('yourpath/wp-blog-header.php');

global $wpdb;

$result=$wpdb->get_results("SELECT * FROM table");

var_dump($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.