Display specific image when a file is missing - php

I'm a beginner to coding and need a little help. I have a code that shows an image according to a specific value in a column of a MySQL table like this:
//Show last 10 added by ID
$sql = "(SELECT * FROM food_tbl ORDER BY food_id DESC LIMIT 10) ORDER BY food_id ASC;";
$result = $conn->query($sql);
$pathImg = "/images/";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$pathFile = $pathImg . $row['food_name'] . ".jpg";
echo '<img src="' . $pathFile . '">';
}
}
This outputs, for example, banana.jpg ... The thing is... I would like to show a standard image when files don't actually exist, as in, if I don't have a file called banana.jpg in my "/images/" directory it would show a unknownfood.jpg file instead (which would indeed be inside that directory of course).
Now, here's the thing, I've already found some stuff over here: --- Display specific image depending on specific text in MySQL table using PHP
... and I ended up trying this:
while($row = $result->fetch_assoc()) {
$pathFile = $pathImg . $row['food_name'] . ".jpg";
if (file_exists($pathFile)) {
echo '<img src="' . $pathFile . '">';
} else {
$pathFile = $pathImg . "unknownfood.jpg";
echo '<img src="' . $pathFile . '">';
}
}
Now, what this does is this will completely ignore the files that are actually there. For example, if I try showing banana.jpg it will instead show unknownfood.jpg.
I'm pretty sure it's something really easy that I'm screwing up, or something I'm not using the way it's intended to. Thanks for the help!

When you're in PHP, using file_exists($pathFile) is the path on the server, relative to the document root (which could be /public_html/youruser), while the HTML reads from the base-folder (off the domain, /).
This means your code would have to look something like this
if (file_exists($_SERVER['DOCUMENT_ROOT'].$pathFile))

file_exists will check a filesystem path, for example /home/www/images/banana.jpg.
When you display the img tag, it will pull the image from the doc root, domain.com/images/banana.jpg.
Find the correct file system path and pass it to file_exists, it will return the correct answer.
Right now it will always return false so you will end up in the else part of the if clause.

Related

How to query a file path from MySQL table and get it to display as a link

I need to figure out how to query several columns of data into a table on my webpage using PHP and get one column to display as clickable audio files. In my MySQL table the audio column consists of absolute paths to audio files saved in a folder on the disk of my web host. All attempts so far have only succeeded in querying the file path as text, not as clickable audio.
I've been using a PHP loop statement to try to query several data columns into a table, like this:
<?php
$sql = "SELECT id, word, audio FROM dictionary";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["word"]. " " . $row["audio"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Here's a photo of my table with one record in it:
enter image description here
But I've also tried the URL in place of the absolute path: https://memoriaelinguagrumentina/dictionaryAudio/a1.com
In either case, the path displays as text.
Any suggestions on how to get the audio to display on my webpage as something clickable?
You have to output the $row["audio"] as a HTML a tag, but the absolute path is not always the path the file is accessible from outside.
The PHP code should look like something like this:
echo "id: ".$row["id"]." - Name: ".$row["word"]." <a href='".$row["audio"]."'>Click here to play audio</a><br>";
But for example if your audio file's path is /var/www/website/files/01.mp3 this isn't the path that can be used as a http link. You should convert it to a useable URL. If in the above example, your domain is website.com and your document root on the server is the /var/www/website you should do something like this:
func FilePathToURL($fp) {
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
return $protocol."://website.com".substr($fp, strlen("/var/www/website"));
}
And use this function to echo the correct link like:
echo "<a href='".FilePathToURL($row['audio'])."'>Click here</a>";
You would just need to change it so the echo that you output to the page is wrapped in an anchor tag something like this. You'll need to add in the href where it is going to be going based on your data tho.
echo "<a href=''>" . "id: " . $row["id"]. " - Name: " . $row["word"]. " " . $row["audio"] . "</a>" . "<br>";
Since your audio values begin with "/public_html/...", you need to remove that leading string since presumably your web root already points there:
echo 'id: ' . $row['id'] . ' - Name: ' . $row['word'] . '<br>';
This should result in HTML that looks something like:
id: 1: - Name: word<br>

Broken image icon displays while trying to display a BLOB

Okay, so my end goal is to display an image (or multiple in a blog type style) that is stored in a database(MySQL) as a blob. Right now it display a broken image icon (). This is what I've tried so far:
<?php
$link = mysql_connect('HOST','USER','PASS!') or die("Could not connect to database");
$dbsel= mysql_select_db('DATABASE', $link) or die("Couldn't select database.");
$result = mysql_query("SELECT * FROM bmblog");
while($row = mysql_fetch_assoc($result))
{
echo "<img src='php/imgView.php?imgId=".$row['media']."' />";
echo "<center>" . "<font color='white'>" . "<FONT FACE='timesnewromans'>" . nl2br(htmlspecialchars($row['msg']));
echo "<br>";
echo "<br>";
};
?>
Also
echo "<img src='data:image/jpeg;base64," . base64_encode($row['media']) . '" />';
echo "<center>" . "<font color='white'>" . "<FONT FACE='timesnewromans'>" . nl2br(htmlspecialchars($row['msg']));
Both display the same broken image icon. I did notice however without trying to echo the second line (of text) I did get a full boarder around the broken image icon that would have been about the size of the image. This is not the same for the first method though.
I've been searching for a few hours now and have found tons of post about this, but none that seemed to work for me or make sense, I am fairly new to PHP so this may be something simple I am missing; Either way thank you in advance for any help it is greatly appreciated!
What might solve the problem is the to add header("Content-Type: image/jpeg"); just before you print/echo the image.
Also it is strange that base64 example you included would not have worked. When I looked at the example provided, the first line of the Also section the echo opens with double quote(") and end with single quote('). This might cause exception and why you couldn't test base64 properly.
It must be:
echo "<img src='data:image/jpeg;base64," . base64_encode($row['media']) . '" />";
You can also add a charset: data:image/jpeg;charset=utf-8;base64,
Lastly, I would suggest looking at the following example that might help
How to Base64 encode your images

php replace database result with an image

This is the first time I have ever posted a question. I am a newbie, and I hope I get all the formatting correct in this message. I love stack overflow. It has helped me get through many challenging situations. But this one has me stymied.
I would like to replace a MySQL database result with an image. I have a plant database that I'm querying to show lists of plants. My results table consists of the plant type, the botanical name, the common name, and whether it is a native plant.
The result for the native plant comes in from the database as the letter 'y' (for yes). I would like to replace that 'y' with an image of an oak leaf. The code I'm currently using displays the oak leaf on all plants, not just the ones that are native plants.
What to do? I feel like I need to insert an if statement in the while loop, but it never works when I try it. I've tried tons of different solutions for a few days now, and would like to ask for help with this.
Here's the latest code I've got that displays the image for every plant, not just the natives:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$native_image = $row['native'];
$image = $native_image;
$image = "images/oak_icon.png";
echo '<tr><td>' .
$row['plant_type'] .
'</td><td>' .
$row['botanical_name'] .
$row['common_name'] .
'</td><td>' .
$image .
'</td></table>';
}
I hope I understood your question.
Some of rows in MySQL have $row['native'], that are equals 'y'. If it is so, then you are on the right way - you have to put an if statement in your loop.
Try it
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
if ($row['native'] == "y") {
//we show our image
$image = "images/oak_icon.png";
} else {
//we don't have to show our image
$image = "";
}
echo '<tr><td>' .
$row['plant_type'] .
'</td><td>' .
$row['botanical_name'] .
$row['common_name'] .
'</td><td>' .
$image .
'</td></table>';
}
And where is your IMG tag? =)
For the future: In my Projects, if I want to save the information about image, that belongs to the row in MySQL, I just save the name of the picture, where it has to be, and if not, i save the name of empty 1x1 PNG image (usual "blank.png"). If you put blank.png in an IMG tag, that has fixed height and width, so IMG takes just the place on your page.
I hope I helped you, and this is my first Answer! =)
P.s. sorry for my english...
Explosion Pills is correct. You will need to check if the $row['native'] is 'y' then set the image html to whatever is required. Hope this helps.
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$image='';
if($row['native']=='y'){
$image = '<img src="images/oak_icon.png" />';
}
echo '<tr><td>' .
$row['plant_type'] .
'</td><td>' .
$row['botanical_name'] .
$row['common_name'] .
'</td><td>' .
$image .
'</td></table>';
}

How to Show Images from File System with PHP

Okay, so I have a database that stores the name of an uploaded file in a column called filename.
I am trying to use PHP to show that file (stored in the file-system, not database) by taking the filename as stored in the database and concatenating it onto the HTML tag, like so:
$stmt = $db->dbh->query("SELECT id, filename FROM images");
$stmt->setFetchMode(PDO::FETCH_BOTH);
$path = '';
while ($row = $stmt->fetch()) {
$path = 'i/' . $row['filename'];
echo "<img src=" . $path . "/>";
}
However, it's not showing anything. What am I doing wrong, or what is a better way to accomplish this?
You are missing quotes around the image file name. Try this:
echo '<img src="' . htmlspecialchars($path) . '"/>";

Limiting a results Flickr Api to avoid duplicate photos from a user?

Trying to output flickr images from a certain location, not using any geolocation yet, only the a string of the location, but thats a problem for another topic :).
Problem is that when I call flickr.photos.search for that place, I may get a few results from a single user. Is there any easy way in PHP to limit this, but still maintain the number of images I request?
Rather than having the output populated with a few users, I would like to have 12 images each by different users. I know this is easily possible, but its on the tip of my brain and I cant seem to write it.
Here is what I have far.
`
$users = array();
foreach($rsp->photos->photo as $photo)
{
$photo_owner = $photo["owner"];
$photo_id = $photo['id'];
$photo_title = $photo['title'];
$photo_url = "http://flickr.com/photos/" . $photo_owner . "/" . $photo_id . "/";
$flickr_getSizes = "http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=$api_key&photo_id=$photo_id";
// If its not in an array, add it and output the image
if (!in_array($photo_owner, $users)){
array_push($users, $photo_owner);
$flickr_getSizes = "http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=$api_key&photo_id=$photo_id";
$sizes_rsp = getXML($flickr_getSizes);
foreach($sizes_rsp->sizes->size as $size){
if ($size['label'] == $preferredSize) {
echo '<li>';
echo '<img src="' . $size['source'] .'"/>';
echo '<h3>' . $p_title . '</h3>';
echo '</li>';
}
}
}
}`
There is more above but its only getting the XML.

Categories