How to upload and store files to the mysql database using php

Source: Internet
Author: User
Tags php file upload
This article mainly introduces how php uploads files and stores them to the mysql database. It analyzes in detail the php file upload and database storage techniques in the form of a complete instance, useful for reference and friends

This article mainly introduces how php uploads files and stores them to the mysql database. It analyzes in detail the php file upload and database storage techniques in the form of a complete instance, useful for reference and friends

This example describes how to upload files to the mysql database using php. Share it with you for your reference. The specific analysis is as follows:

The following code creates a mysql table and uploads a file to the mysql database.

Create a mysql table:

<? Php $ con = mysql_connect ("localhost", "", ""); mysql_select_db ("w3m"); $ SQL = "CREATE TABLE updfiles (". "id integer not null AUTO_INCREMENT ". ", name VARCHAR (80) not null ". ", type VARCHAR (80) not null ". ", size integer not null ". ", content BLOB ". ", primary key (id )". ")"; mysql_query ($ SQL, $ con); mysql_close ($ con);?>

Upload the file and save it to mysql. insert it using the insert statement.

<? Php $ con = mysql_connect ("localhost", "", ""); mysql_select_db ("w3m "); $ error = $ _ FILES ['w3img '] ['error']; $ tmp_name = $ _ FILES ['w3img'] ['tmp _ name']; $ size = $ _ FILES ['w3img '] ['SIZE']; $ name = $ _ FILES ['w3img'] ['name']; $ type = $ _ FILES ['w3img '] ['type']; print ("\ n"); if ($ error = UPLOAD_ERR_ OK & $ size> 0) {$ fp = fopen ($ tmp_name, 'R'); $ content = fread ($ fp, $ size); fclose ($ fp); $ content = addslashes ( $ Content); $ SQL = "INSERT INTO fyi_files (name, type, size, content )". "VALUES ('$ name',' $ type', $ size, '$ content')"; mysql_query ($ SQL, $ con); print ("File stored. \ n ");} else {print (" Database Save for upload failed. \ n ");} print (" \ n "); mysql_close ($ con);?>

I hope this article will help you with php programming.

,

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.