Reputation: 57
I have a MySQL query that is not working and I'm not sure why.
Here is my code for selecting the id from the url and using it as a variable so Mysql can return the img_url column.
<?php
global $wpdb;
$table_name = $wpdb->prefix . "photos";
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$id = basename(parse_url($url, PHP_URL_PATH));
$image = $wpdb->get_results("SELECT img_url FROM $table_name WHERE id = $id");
echo $id
?>
and then to show my image
<img src='<?php echo $image; ?>'>
The result I get back from MySQL is "array". I don't know if it matters but the id column is AUTO_INCREMENT PRIMARY KEY. Also, I know "echo $id" does return the the id from the url so I know it works. Any suggestions? Thanks.
Upvotes: 0
Views: 605
Reputation: 31832
To return a single value (one column from one row) you can use wpdb::get_var
$image = $wpdb->get_var("SELECT img_url FROM $table_name WHERE id = $id");
$echo $image;
If you use wpdb::get_results you will get an arry of rows. In this case you would need to access the value with $image[0]['img_url']
or with $image[0]->img_url
- depending on the fetch mode.
Since the $id
is a user input you should also use wpdb::prepare
$query = $wpdb->prepare("SELECT img_url FROM $table_name WHERE id = %d", $id);
$image = $wpdb->get_var($query);
$echo $image;
Upvotes: 2
Reputation: 1722
To determine the exact type of a value, you can use:
echo var_export($value, true);
So in your case:
echo var_export($image, true);
With this debug line, you should see that $image
is an array and its content.
Update:
It returns
array( 0 => stdClass::__set_state(array( 'img_url' => 'wallbate.cc/image/IMG_0026.jpg';, )), )
You probably want the image url, to do so, I think you have to do:
$image_url = $image[0]['img_url']
<img src='<?php echo $image_url; ?>'>
Upvotes: 0