Jump to content

database image loader


Q695

Recommended Posts

How do I create an image from a database if there's one avalible, or if there isn't one I use a default photo?

 

Here is what I have so far:

<?php
include "../link/log.php";
include "../link/dead.php";

$sql="SELECT * FROM players WHERE id='$id';";
$result=@mysql_query($sql, $con) or die(death($sql));
$u_row=mysql_fetch_array($result);

if ($u_row[image]){
echo $u_row[image];
} else {
?>
<img src="sword.jpg">
<?php
}
?>

 

note:The two other files are in a different folder at the same level.

Link to comment
Share on other sites

Your code has the right logic, but there are just a few problems.

 

1. Unless you are needing the other fields, just query for the image.

2. You need to enclose the array index name within quotes.

3. You are only checking if the query returns a value for "image". You need to check if the value contains anything. I think that check might work if you are setting the value as NULL, but it won't work if the value is an empty string - which is what most people do

4. Unlsee you are storing the image as the complete html source to display the image (not recommended) you need to add the HTML tags to the path.

 

here is how I would do it:

<?php
include "../link/log.php";
include "../link/dead.php";

$sql="SELECT img FROM players WHERE id='$id';";
$result=@mysql_query($sql, $con) or die(death($sql));
$u_row=mysql_fetch_array($result);

//Determine the image to display
if ($u_row['image'] != '')
{
    $img = $u_row[image]; //Add the appropriate path
} else {
    $img = "sword.jpg"; //Add the appropriate path
}

//Display the image
echo "<img src=\"{$img}\">";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.