SQL Query inside Widget

I have a widget which contains the following code:

<? global $wpdb;
$querystr = "SELECT name FROM wp_venues WHERE name="".the_field("venue')."' ";
$info = $wpdb->get_var($querystr);
echo $info;
?>

What I need is to be able to use the information from the table and format it, so

Name:
Capacity:
Image:
Description:

At the moment I am only able to retrieve 1 field, I think get_rows would help but how am I able to separate the fields so I can format.

Thanks

1 Answer
1

"SELECT name FROM wp_venues WHERE name="".the_field("venue')."' ";
will only return the value of the_field('venue') which is already known.

"SELECT * FROM wp_venues WHERE name="".the_field("venue')."' "; will select the whole row with all fields.

Try too use $wpdb->prepare for security reasons.

With $wpdb->get_row you get the whole row as either an object, a numerically indexed array or an associative array. See the codex on get_row.

For example you could do the following:

$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM wp_venues WHERE name = %s", the_field('venue')));
echo "Name: ".$row->name."\n";
echo "Capacity: ".$row->capacity."\n";
echo "Image: ".$row->image."\n";
echo "Description: ".$row->description."\n";

Debugging

Try what is mentioned in the codex : http://codex.wordpress.org/Class_Reference/wpdb#Show_and_Hide_SQL_Errors and turn on WP_DEBUG in wp-config.php.

In addition : $wpdb->last_query can be looked up to show the last query used. Retrieve the query, that is actually executed and try this query manually and see which results there are.

Literature

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

Leave a Comment