使用PHP上传和从MySql服务器检索图像的示例代码

时间:2011-10-26 16:32:40

标签: php mysql blob

如何使用PHP从MySql数据库上传和检索图像。我需要示例代码将图像转换为二进制等效,反之亦然,以便可以以BLOB格式存储和检索MySql数据库。我尽力在线,但我不能。任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:2)

检查此链接,他们可能会帮助您开始使用

storing images in mysql

How to Store images in mysql database with php

答案 1 :(得分:0)

CREATE TABLE `pix` 
  ( 
     `pic_id`   INT(11) NOT NULL auto_increment, 
     `pic_name` VARCHAR(100) NOT NULL, 
     `pic_data` LONGBLOB NOT NULL, 
     PRIMARY KEY (`pic_id`) 
  ) 
engine=innodb 
DEFAULT charset=latin1; 

获取2个php文件: - Image.php,showImage.php。

相应地设置连接参数。

/* Image.php*/

<?php

    $con = mysql_connect("127.0.0.1:3306", "root", "");

    if (!$con) {
        die("Could not connect: " . mysql_error());
    }

    $DB = mysql_select_db("test", $con);
    move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], "latest.img");
    $instr = fopen("latest.img","rb");
    $image = addslashes(fread(fopen("latest.img","r"),filesize("latest.img")));
    mysql_query ("insert into pix (pic_name, pic_data) values ("myImage", "'.$image.'");");

?>
<html>
    <form enctype="multipart/form-data" method="POST">

        <img src=showImage.php?gim=1 width=500 height=150 alt="hell">

        <br>
        <hr>

        <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload(
        <100 KB): <input name="uploadedfile" type="file" />
        <br/>

        <input type="submit" value="submit" name="submit" />    
    </form>
<html>
/*showImage.php*/

<?php

    $con = mysql_connect("127.0.0.1:3306", "root", "");

    if (!$con) {
        die(“Could not connect: ” . mysql_error());
    }

    $DB = mysql_select_db("test", $con);
    $res = @mysql_query("select * from pix order by pic_id desc limit 1");

    if ($row = @mysql_fetch_assoc($res)) {

        $title = htmlspecialchars($row[pic_name]);
        $bytes = $row[pic_data];

    }

    header("Content-type: image/jpg");
    print $bytes;
    mysql_close();
?>