0

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.

2
  • Its probably returning array with one row with your img url... try <img src='<?php echo $image['img_url']; ?>' > or check how $image variable is structured with print_r($image); Commented May 3, 2017 at 15:51
  • Try $image = $wpdb->get_var("...") wpdb::get_var Commented May 3, 2017 at 16:05

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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; ?>'>

1 Comment

It returns array ( 0 => stdClass::__set_state(array( 'img_url' => 'wallbate.cc/image/IMG_0026.jpg', )), )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.