0

What is the correct way to query a WordPress database?

I would like to achieve a similar output as seen in the links section of WordPress Dashboard so as to be able to perform edit and delete operations on given table rows / columns, individually.

I've made use of knowledge drown from several articles on setting up database tables in WordPress and as such was able to build the front-end so as to accommodate both edit and delete operations; what I currently need is a solid example of how to make use of the WordPress database query API in order to perform all CRUD operations.

  • use wpdb to query database, read more about it in codex codex.wordpress.org/Class_Reference/wpdb – Eugene Manuilov Jun 4 '12 at 20:15
  • Thanks Eugene, the codex has definitely helped, I guess it's difficult for me because I need the query to return results into a table format, so I'm stumped. In other words, how can I format the query to output results in a table format? – Rob Myrick Jun 4 '12 at 20:28
1

Querying in WordPress is done by using the the wpdb variable. Be sure to always prepare your sql so WP can make it database safe.

Example:

global $wpdb;
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$wpdb->prefix}TABLE_NAME` WHERE `var` = %d", 1) );

Then you can loop through the data and output it as for example a table (table formatting not included).

foreach($rows as $row) 
{
  echo $row->post_title;
}

Please note that the SQL query above doesn't work because it contains dummy data. Please change it so it fits your needs.

  • OK, Barry the idea makes sense......so echo $row->post_title; would take care of the row display only, or would that also display the columns as I need? – Rob Myrick Jun 4 '12 at 20:59
  • The echo $row->post_title; would only display the title of the post. If you would like to display a row with a single column that would display the title, you can do echo "<tr><td>{$row->post_title}</td></tr>\n";. – Barry Kooij Jun 4 '12 at 21:02

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.