Need one line of php...spent hours already. $wpdb

Ok, I’ve spent hours trying to work out the syntax and format and command to use. My need is simple and once I can see how this l ine should look, I should be able to develop it further myself.

I want to take one piece of data from the wp database and put it in an array. Simple!

Nearest I have come up with is:

$mybit = $wpdb->get_results("SELECT meta_value FROM $wpdb->$postmeta WHERE meta_id = ‘46’ ");

The data I need is in a table called wp_postmeta, and is on the same row as meta_id 46. I want the meta_value to be assigned to $mybit.

I must be close!!!

Can this be called from the root directory? Do I need to set up anything else? Globe etc. Can one line of stand alone code do this or do I need an environment?

Your code seems to be correct. You can call it from anywhere but you just need to declare this before the query

[php]
global $wpdb;
/*
*your query
*/
[/php]

Thanks for that. I put that line in but still cannot get past this line:-

$mybit = $wpdb->get_results("SELECT meta_value FROM $wpdb->$postmeta WHERE meta_id = ‘46’ ");

I have an echo line after this which does not get reached.

try this :

[php]$mybit = $wpdb->get_results("SELECT meta_value FROM wp_postmeta WHERE meta_id = ‘46’ ");[/php]

No. Still no good :frowning:

Will investigate further today.

hmmm…do i need to open connection and pass the login details etc? Thought $wpdb took care of this.

No, you don’t need to. $wpdb takes care of it.

try to echo the query and post it here.

This is crazy!

Simplest standard command on a standard WP installation.

<?php global $wpdb; $numpost = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'"); echo $numpost; ?>

Gives
Fatal error: Call to a member function get_var() on a non-object in /home/pittsbur/public_html/textfromdb.php on line 3

Surely the problem must lie elsewhere i.e. not my code.

Try following and post here what happens :

[php]<?php
global $wpdb;
$numpost = $wpdb->get_var($wpdb->prepare(“SELECT COUNT(*)
FROM $wpdb->posts
WHERE post_status = ‘publish’ AND post_type = ‘post’”));
echo $numpost;
?>[/php]

If it still doesn’t work, put [php]<?php $wpdb->show_errors(); ?>[/php] after the query and run again.

Sponsor our Newsletter | Privacy Policy | Terms of Service