开发者

weird characters instead of an image when dispalying from mySQL

I'm trying to display a blob image from mySQL, and I'm getting weird characters instead.

To insert data I use:

  if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

  // Temporary file name stored on the server
  $tmpName  = $_FILES['image']['tmp_name'];  

  // Read the file 
  $fp      = fopen($tmpName, 'r');
  $data = fread($fp, filesize($tmpName));
  $data = addslashes($data);
  fclose($fp);

// Insert data into mysql
$sql="INSERT INTO $tbl_name( image )VALUES('$data')";
$result=mysql_query($sql);
}

To display:

$tbl_name="table"; // Table name
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);

if (!$result) {
echo "There is nothing";
}

while($rows= mysql_fetch_assoc($result)){

//header('Content-type: image/jpg'); 
 echo $rows['image'];

?>

How can I fix that? Thank you i开发者_Python百科n advance.


First, it's best practice to not store images in your database. Store them in a folder instead.

Second, you are seeing the raw data of the image in ASCII.

To answer your question if you must store images in a database, make a new php file.

header('content-type: image/png'); // Use a variable for the image type
// Code here to select a single image from the database.
// Echo the database value.

Call the picture with

<img src="link_to_php_file.php" alt="" />


You need to send an image header, like:

header("Content-Type: image/png"); // or image/jpeg or image/gif

Keep in mind that you can only show one image per time and nothing else.

If you want to show multiple images on a webpage you will need to simply link to them:

<img src="getimage.php?id=1234" />
<img src="getimage.php?id=1235" />
<img src="getimage.php?id=1236" />

Where getimage.php contains the code that will send the Content-Type header and fetch the data BLOB from MySQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜