ElaGorilaki
ElaGorilaki

Reputation: 227

Displaying image from a database

I have heard that is a very bad idea to save images in the database so I decided to save the path of the image. The problem here is that I can t find a way to show the image. I tried this

<?php
$con = mysql_connect("localhost","root","mypassword");
mysql_query('SET NAMES UTF8');


if (!$con)
{
    echo "problem with connection" .mysql_error();
}
?>
<?php
mysql_select_db("eshop",$con);
$result = mysql_query("SELECT * FROM products", $con);
    $row = mysql_fetch_array($result);
while ($row)
 {   
$myimage = '<img src="<?php echo $row[\'image\']; ?>" />';
echo $row['title'] . " " . "<br />" . $myimage . $row['category'];
$row = mysql_fetch_array($result);
 }
 mysql_close($con);
?>

and other similar ways with no result. Anyone has a clue on this?

Upvotes: 0

Views: 270

Answers (2)

Constantine Loukas
Constantine Loukas

Reputation: 292

Why are there php opening and closing tags in there? You can just do:

$result = mysql_query('SELECT * FROM products',$con);
while($row = mysql_fetch_array($result)){
$myimage = '<img src="'.$row['image'].'" />';
echo $row['title']. ' ' . '<br/>' . $myimage . $row['category'];
}
mysql_close($con);

Please note that mysql_* functions are going to be deprecated in the next version or the one after that. You should use mysqli or PDO instead. Also if you don't intend to have variables inside other variable definition you should use single quotes because php parses strings inside double quotes. It's a bit faster if you use single quotes when needed.

You can see what I mean about single and double quotes here: http://codepad.org/UW5DO2fT

Upvotes: 1

Norse
Norse

Reputation: 5757

You're trying to call $row before you've even set it or called the mysql array.

 $row = mysql_fetch_array($result);
 $myimage = '<img src="<?php echo $row[\'image\']; ?>" />'
 echo $row['title'] . " " . "<br />" . $myimage . $row['category'];

You also want to escape the single quotes around 'image' or you'll get a syntax error.

Upvotes: 3

Related Questions