繁体   English   中英

如何从 MySQL 数据库中存储和检索图像并使用 Php 在 html 中显示它?

[英]How to store and retrieve image from MySQL database and display it in html using Php?

我需要显示来自 MySQL 数据库的图像列表并显示图像。 在这里,我的示例代码可用于插入,但没有显示任何内容..任何人都可以帮助我..

$file = fopen("switch.jpg", "rb");
$image = fread($file, filesize('switch.jpg'));
$image = base64_encode($img);
$ins_query="INSERT INTO mytable (id,imag) "."VALUES ('','$img')";
mysql_query($ins_query)or die('Error in query !');
$id1=1;
echo "inserted ";
 $query="select imag from mytable where id='$id1'";
     $result=mysql_query($query) or die("Error: ".mysql_error());
     $row=mysql_fetch_array($result);
     echo '<img src="data:image/jpeg;base64',base64_encode($row['imag']).'"/>';
fclose($file);

你做错了两件事:

  1. 缺失,数据之后:图像/jpeg;base64
  2. 重新编码 base64 数据

所以,这是我的修复,试试这个:

...
echo '<img src="data:image/jpeg;base64,',base64_decode($row['imag']).'"/>';
fclose($file);

尝试将图像路径或文件名存储在数据库中,而不是将二进制数据保存在数据库中。 将图像存储在您的系统文件夹中。 这可能会更快

为了获取图像,只需获取图像路径或名称并将其显示在您的 html 页面中

echo '<img src="<?php echo FULL_BASE_URL.'/'.$imagePathfromDB; ?>"/>';

在您的情况下,如果 ID 是自动递增的,则不要插入它。 它会自动插入

<?php
$number_of_thumbs_in_row = 4;

        $result = mysql_query( "SELECT photo_id,photo_caption,photo_filename,photo_category FROM gallery_photos");


            while( $row = mysql_fetch_array( $result ) )
            {
                $result_array[] = "<img src='".$images_dir."/tb_".$row[2]."' border='0' alt='".$row[1]."'/><br>$row[1]<br>$row[3]<br>$row[0]";

            }
            mysql_free_result( $result );   

            $result_final = "<tr valign='top' align='center' class='style1'>\n";

            foreach($result_array as $thumbnail_link)
            {

                if($counter == $number_of_thumbs_in_row)
                {   
                    $counter = 1;
                    $result_final .= "\n</tr align='center' class='style1'>\n<tr align='center' class='style1'>\n";

                }
                else

                $counter++;

                $result_final .= "\n<td class='style1'>".$thumbnail_link."</td>\n";


            }


            if($counter)
            {

                if($number_of_photos_in_row==$counter)
            $result_final .= "\n<td class='style1' colspan='".($number_of_photos_in_row=$counter)."'></td>\n";

                $result_final .= "</tr>";

            }

        }

echo <<<__HTML_END

<html>
<head>
    <title>Gallery View</title>
</head>
<body>
<table width='100%'  border='0' cellpadding="10" cellspacing="10">
$result_final   

</table>
</body>
</html>

__HTML_END;
?>

只是通过这篇文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM