Can't load image from MySQL database with PHP - php

I'm creating a list of articles inside a section, but I'm having troubles getting the images out of my MySQL database. I followed this guide how to store images in MySQL http://forums.mysql.com/read.php?20,17671,27914. This is the code I'm using.
<?php
$result = mysql_query("SELECT * FROM heroes");
while ($row = mysql_fetch_array($result)) {
echo "<article>";
if($row{'Type'} == 'Strength') {
echo "<span class='strength'></span>";
} elseif ($row{'Type'} == 'Agility') {
echo "<span class='agility'></span>";
} else {
echo "<span class='intelligence'></span>";
}
echo "<div>";
echo "<header>"."<h2>"."<a href='javascript:;'>".$row{'Name'}."</a>"."</h2>"."</header>";
if($row{'Image'} != NULL) {
?>
<img src="<?php base64_decode($row{'Image'}); ?>" alt="hero-image" width="200" height="300" />
<?php
} else {
echo '<img src="images/no-image.png" alt="hero-image" width="200" height="300" />';
}
echo "</div>";
echo "</article>";
}
?>

replace your image source with
'data:image/gif;base64,'.base64_decode($row{'Image'});
also use proper mime instead of gif

There are a few things wrong with your code:
You call mysql_fetch_array but then use curly braces which are meant for objects, yet you have an array.
You call base64_decode. This means that you will get binary content into your HTML which won't work. You have to encode it with base64_encode if it is stored in binary form.
The value of the src of a <img> must be a URL, not the content itself. In your case you can use a Data-URL.

Related

If image exists show else hide it

I have the following situation.
If there isn't an image in the DB, the page it's on shows a big image placeholder. What is the best way to hide the image placeholder if an image doesn't exist?
<img src="<?php echo '../img/artists/' . $row_rsAccents['artistPhoto']; ?>" width="100%"/>
http://westerndesignconference.com/intheloop/
You can do this with a simple if/else statement like so:
//I prefer to set things with variables
$placeholder_img = "../img/artists/placeholder.jpg";
$db_img = $row_rsAccents['artistPhoto'];
if($db_img){
$img_src = $db_img;
} else {
$img_src = $placeholder_img;
}
echo "<img src='$img_src' alt='' width='100%' />";
If there is a value returned - show an image. If the condition fails, no <img> will be displayed, preventing the blank gap
if (isset($row_rsAccents['artistPhoto'])) {
echo '<img src="../img/artists/' . $row_rsAccents['artistPhoto'] . '" width="100%"/>'
}
if (file_exists('artist.jpg') {
echo "<img src='artist.jpg'>";
}
else {
echo "<img src='default.jpg'>";
}

If statement within echo?

I was wondering if it's possible to have an if statement within an echo.
I have if statement which works fine when echoing results through the a while loop... This is the statement:
<div><?php if ($row['image'] == '') {}
else {echo "<img src='data:image/jpeg;base64,".base64_encode($row['image'])."'>";} ?>
<?php if ($row['video'] == '') {}
else {echo "<iframe src={$row['video']}></iframe>";} ?></div>`
So basically it's either a video or an image which works fine but then I implemented an infinite scroll to my blog which echoes the data from the database through and if statement like so:
if ($results) {
while($obj = $results->fetch_object())
{
echo '
<div><h3>'.$obj->headline.'</h3> </div>
<div><img src='data:image/jpeg;base64,".base64_encode('.$obj->image.')."'></div>'
So I wondering if anyone knows if it's possible to transfer that if statement within this echo so that it display an image firstly and then knows whether one is present or when a video is present within the database.
Thanks in advance for any help.
PS: I'm very new to coding/php!
Of course. Just split up the echo into multiple statements:
while($row = $results->fetch_object()) {
echo '<div>';
if ($row['image'] == '') {
} else {
echo "<img src='data:image/jpeg;base64,".base64_encode($row['image'])."'>";
}
if ($row['video'] == '') {
} else {
echo "<iframe src={$row['video']}></iframe>";
}
echo '</div>';
}
Try this one.
//first initialize a variable as a string
$result="";
while($obj = $results->fetch_object()) {
$result.="<div>";
if (!empty($obj['image'])){
$result.="<img src='data:image/jpeg;base64,".base64_encode($obj['image'])."'>";
}
elseif (!empty($obj['video'])){
$result.="<iframe src={$obj['video']}></iframe>";
}else{
//show some notification or leave it
//echo 'not Found';
}
$result.="</div>";
}
//finally you need to print the result variable.
echo $result;

Load XML Sources and show mixed content

What is the way to load more than one XML (different sources) and show a mixed content?
My Code is now loading only one XML now
<?php
$mobile = simplexml_load_file('mobile.xml');
$electronics = simplexml_load_file('electronics.xml');
foreach($mobile->product as $product)
{
echo '<div class="col-md-3">'."\n";
echo '<h4 class="img-responsive">'.$product->name.'</h4>'."\n";
echo '<p><img src="'.$product->image->large.'" class="img-responsive" /></p>'."\n";
echo '<p>'.$product->Price.'</p>'."\n";
echo '</div><!--end painting_record-->'."\n";
}
foreach($electronics->product as $product)
{
echo '<div class="col-md-3">'."\n";
echo '<h4 class="img-responsive">'.$product->name.'</h4>'."\n";
echo '<p><img src="'.$product->image->large.'" class="img-responsive" /></p>'."\n";
echo '<p>'.$product->Price.'</p>'."\n";
echo '</div><!--end painting_record-->'."\n";
}
?>
Thanks
Mix them how? It looks like your code would show them all in one list with mobile on the top and electronics at the bottom. I guess you could do something like (paracoding here)...
foreach($mobile->product as $product) { array_push($newList,$product); }
foreach($electronics->product as $product) { array_push($newList,$product); }
Then do a foreach on $newList, but sorting them however you want.

.load into DIV with PHP content

I am trying to .load a script called 'refreshImages.php'. Inside that script is a while loop pulling from the database. I have got it to load a single echo function but it wont load anything inside the while loop I have on the script... this is what the php file has...
<?php
include 'includes/config.php';
$pimages = mysql_query("SELECT * FROM property_images WHERE pid='$pid'");
//Cant Post Images So Leaving The Echo Content Out//
while($img = mysql_fetch_array($pimages)){
$image = $img['image'];
$image_alt = $img['image_alt'];
echo "<li>$img</li>";
}?>
I am using .load('refreshImages.php') on the page I need it to show up on.
Any explanation I am not seeing?
Your $img is an array, not a string. You will get output like <li>Array</li>, if you have stuff coming from the database. Is that what you mean? Or are you getting an empty result?
If empty - what does your mysql_num_rows tell you when ran against the result resource?
try changing this:
echo "<li>$img</li>";
to
echo "<li><img src=\"{$image}\" alt=\"{$image_alt}\" /></li>";
You may not be getting any results from the database. Try using this code which will display a message if there is something wrong with your sql query.
<?php
include 'includes/config.php';
$pimages = mysql_query("SELECT * FROM property_images WHERE pid=" . $pid );
if (mysql_num_rows($pimages) > 0) { // checks to see if you are getting results from db
while($img = mysql_fetch_array($pimages)){
$image = $img['image'];
$image_alt = $img['image_alt'];
echo '<li><a class="thumb" href="{$image}"><img src="{$image}" width="50px" height="50px" alt="{$image_alt}"></a></li>';
}
} else {
echo "no results returned from database";
} // end of mysql_num_rows check
?>
You might be better off concatenating all the images and then echo-ing it out rather than echo-ing each one e.g
$htmlOutput = '';
while($img = mysql_fetch_array($pimages)){
$image = $img['image'];
$image_alt = $img['image_alt'];
$htmlOutput .= "<li><img src=\"{$image}\" alt=\"{$image_alt}\" /></li>";
}
echo $htmlOutput ;

PHP If else statement that a database record is empty it will display a default picture

Hi basicly I am trying to create a simple IF statement that shows a default picture if one hasn't been entered in to my database. I am using server to store my picture and a database to store the file name, so I can get the image to display if it has a file name in the db but I want the If statement to say if the record is empty display this default image. I have some code here that I have tried however it doesn't work any thoughts? I tried a few other ways of doing it but they didn't work either.
Cheers.
Code so far:
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM db*****") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<div class="member">
<div class="imageSection">
<?
if($info['photo'] == '')
{echo "<img class=\"memberImage\" src=images/default.jpg>";}
else {echo "<img class=\"memberImage\" src=images/".$info['photo'] .">";}
?>
</div>
<div class="memberInfo">
<? Echo "<p><strong>Name: ".$info['nameMember'] . "</strong></p>";
Echo "<p>Position: ".$info['bandMember'] . " </p>";
Echo "<p>About Band Member ".$info['nameMember'] .":".$info['aboutMember'] . "</p>";
Echo "<p>Other Bands: ".$info['otherBands'] . " </p><br/></div></div><br class=\"clearBoth\"/>";
}
?>
What about a simple ternary:
$photo = ($info['photo'] == null) ? "default.jpg" : $info['photo'];
echo "<img class=\"memberImage\" src=images/". $photo .">";
Are you sure the default value for the column is set to "". it could be set to null? although idk if that would cause it not work.
add the following code before the if statement
echo $info['photo'];
Another suggestion would be to trim the data before comparing it.
You could use file_exists, which will work even if the image is deleted manually.
$photo = 'images/'. $info['photo'];
if (file_exists($photo) == FALSE)
{
$photo = 'images/default.jpg';
}
echo '<img class="memberImage" src="'. $photo .'"/>';
empty() can catch the sort of conditions you are after, so try
if(empty($info['photo']))
{
....
}
empty() returns true if the parameter is '', NULL, false, '0', 0, or an empty array.

Categories