PHP upload image to database sample sharing _php instance

Source: Internet
Author: User
Tags dsn
Most people's image upload is to save a path to the database, so in the insert is really fast, but also in line with the characteristics of the web, but it is very troublesome to delete, need to find the file and delete, the code can be directly stored in the database, deleted. Please note: In this case the database size will proliferate, please use it as appropriate

Table structure
Copy the Code code as follows:
CREATE TABLE ' upload ' (
' id ' int (ten) unsigned not NULL auto_increment,
' type ' varchar (not NULL),
' Data ' Mediumblob not NULL,
PRIMARY KEY (' id ')
) Engine=innodb auto_increment=1 DEFAULT Charset=utf8;

Index.html
Copy the Code code as follows:



<BR> post-image<br>





post.php
Copy the Code code as follows:
if ($_files["file" ["error"] > 0)
{
echo "Error:". $_files["File" ["Error"]. "
";
}
Else
{
$type = $_files["File" ["type"];
$size = $_files[' file ' [' Size '];
$tmp =$_files["File" ["Tmp_name"];
$fp = fopen ($tmp, ' RB ');
$data = Bin2Hex (Fread ($fp, $size));
$dsn = ' mysql:host=localhost;dbname=test ';
Echo '

';
try{
$pdo = new PDO ($DSN, ' root ', ' root ');
$pdo->exec ("INSERT into ' upload ' (' type ', ' data ') VALUES (' $type ', 0x$data)");
$id = $pdo->lastinsertid ();
echo ' Upload success! View ';
$pdo = null;
}catch (Pdoexception $e) {
echo $e->getmessage ();
}
Echo '
';
Fclose ($FP);
}

view.php
Copy the Code code as follows:
$id = $_get[' id '];
if (Is_numeric ($id)) {
$dsn = ' mysql:host=localhost;dbname=test ';
try{
$pdo = new PDO ($DSN, ' root ', ' root ');
$rs = $pdo->query (' select * from ' upload ' where ' id ' = '. $id);
$row = $rs->fetchall ();
$data = $row [0];
Header ("content-type:${data[' Type ']}");
echo $data [' data '];
$pdo = null;
}catch (Pdoexception $e) {
echo $e->getmessage ();
}
}else{
Exit ();
}

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.