Embedding an Image Is Just Viewing an Image PHP Help

Finally, it’s back to <;how_user.php. Remember, show_Image.php was actually a bit of a diversion. It’s a necessary one, but the point isn’t a script that displays an image. Instead, it’s a script that displays a user, and that just happens to mean you have to show that user’s image. But, you have all the work done now to make this happen, so show_user.php is back into the fold, ready for you to piece it all together.

All You Need Is an Image ID

Your first thought might be to rewrite that SQL query that ~abs an entry from IMAGES based on a user from users:

SELECT u.first_name, u.last_name, i.filename
FROM users u, images i
WHERE u.profile_pic_id = i.image_id;

But. do you need to do this? No, because all that show_images.php requires is an image 10, and you have that in the users table, in profile _pic _id. You don’t need to do a join on users and images.

As a result, when you’re getting the results from your SOL query, you just need to grab the profile image ID:

All You Need Is an Image ID

A Script Can Be an Image src

With this 10, you’re ready to deal with the missing image. However, whet’s about to happen might seem a bit odd, so some explanation is in order.

Think about your typical HTML <img> element:

<img src=”/images/powell_kicking.jpg” I>

What’s really happening here? The <img> tag itself informs the browser to expect an image, and’ the src attribute provides the browser with the location of that image. But, that location will just trigger another browser request-in this case, to /images/powell_kicking.jpg And, what does the browser get from that location? A bunch of bits that makes up the image powell.kicking.jpg.

Yet, there’s nothing magical about cowed that URL. It’s just a location, and as long as that location returns an image to the browser, the image is displayed. Thus, it’s perfectly okay to supply anything to the src, as long as that anything returns an image. You might supply it, for example, a script that displays an image. You might just hand it something like this:

<img src=”show_image.php?image_id=4″ I>

Because show image.r;hp with a valid 10 returns an image, the browser happily displays that image in place of the <img> tag in your web page.

From here, it’s a breeze to change your HTML in Show_user.php  to do just this:

All You Need Is an Image ID

That’s all there is to it! The src attribute of your < img> tag is now a link to your script, with the correct ID. When you take all of together, you should have something like this:

A Script Can Be an Image src

You can see the final result in Figure 10-6.

Nice work! Whoever thought before you closed this chapter that you’d be manually loading bits and bytes from a database and displaying them as an image on demand?



Posted on January 12, 2016 in Binary Objects and Image Loading

Share the Story

Back to Top
Share This