0

I am trying to pull data from a table I have imported into my wordpress database.

My php code works for all the default wp_ tables but when try and target the tables I actually want I get bugger all back.

My code (currently echoing all post titles and it works)

$liveposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->posts
 WHERE post_status = 'publish'") );

 foreach ($liveposts as $livepost) {
  echo '<p>' .$livepost->post_title. '</p>';
}

I imported 3 tables from another database, and yes they do have data in to pull out. I found out that the $wpdb->posts expects the posts table to be wp_posts.. so I tried renaming my tables to wp_bus_route... but still nothing.

I used phpMyAdmin to export 3 tables out of a large database (in a .sql format) and imported them. i can see the tables in phpMyAdmin and view all the data in them.

This is my 1st time pulling data from the wp database so I am missing something obvious.

2 Answers 2

7

Referencing the table name like $wpdb->posts only works for standard WP tables. For custom tables, build the table name like this:

$liveposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "tablename WHERE post_status = 'publish'") );

Never, never, never hard-code the prefix. This can be changed in wp-config.php, and many people change it to something other than wp_. Changing it from wp_ is a good security measure. Even if it's your own code and your own site, $wpdb->prefix is a best practice that's worth making into a habit.

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

Comments

2

Try to not using variables at table names:

$liveposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_bus_route
 WHERE post_status = 'publish'") );

3 Comments

Cool, that has done the trick thanks :) Any thoughts on why this works and $wpdb-> does not? And what is the diffence between $wpdb->bus_routes and wp_bus_routes?
It's because wordpress has $tables build in variable described in wp-includes/wp-db.php, where described alloweb tables names array( 'posts', 'comments', 'links', 'options', 'postmeta', 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' ); if you add to this array bus_routes it would work but whatever after wordpress updates to the newer version all your changes will be lost, so use static names of tables instead variables
ok thanks for the insight. makes sense in my head now :) cheers guys

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.