What's wrong with this database query?
-
I’m trying to write a simple custom database query (to go in the template) to get a meta_value from the database, but it’s not working as I’d expect.
The following code works fine:
<?php global $wpdb; $getMeta = $wpdb->get_results( 'SELECT meta_value FROM wp_postmeta WHERE post_id = 492', OBJECT); echo $getMeta[0]->meta_value; ?>It returns the meta_value, which is 4683. But I need the ID to be the ID of whatever page it’s on, so I tried simply swapping it for a variable
<?php global $wpdb; $getId = the_ID(); $getMeta = $wpdb->get_results( 'SELECT meta_value FROM wp_postmeta WHERE post_id = $getId', OBJECT); echo $getMeta[0]->meta_value; ?>…which, for some reason returned the post ID (which incidentally is 492) and not the meta value (4683).
So then I tried this
<?php global $wpdb; $getMeta = $wpdb->get_results( 'SELECT meta_value FROM wp_postmeta WHERE post_id = <?php the_ID(); ?>', OBJECT); echo $getMeta[0]->meta_value; ?>which returned nothing, and finally (thinking that maybe it needed to know the value of the ID before using it in a query, I tried this
<?php ob_start(); echo the_ID(); $getId = ob_get_contents(); ob_end_clean(); ?> <?php global $wpdb; $getMeta = $wpdb->get_results( 'SELECT meta_value FROM wp_postmeta WHERE post_id = $getId', OBJECT); echo $getMeta[0]->meta_value; ?>which, again returned, or at least “echoed” nothing. I’m guessing the answer’s obvious to anyone who knows much about php. But after a few hours of trying to get it to work I could use some advice. I’m using php version 5.4.31 (in case it matters).
The topic ‘What's wrong with this database query?’ is closed to new replies.