If you want to save binary data, such as image files and HTML files, directly in your MySQL database, then this article is for you! I'll show you how to store these files through HTML forms, and how to access and use these files.
Overview of this article:
. Create a new database in mysql
. An example program of how to save files
. An example program of how to access files
Create a new database in mysql
First, you must create a new database in your mysql. We will store those binary files in this database. In the example I will use the following structure. In order to create the database,
you must do the following steps:
. Enter the MySql controller
. Enter the command "create database binary_data;"
. Enter the command "use binary_data;"
. Enter the command
"CREATE TABLE binary_data (id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,description CHAR(50), bin_data LONGBLOB, filename CHAR(50), filesize CHAR(50), filetype CHAR(50));" (Cannot break lines)
If there are no accidents, the database and table should be established.
An example program of how to store files
Using this example, you can transfer files to the database through Html forms.
store.php3
// store.php3 - by Florian Dittmer
?>
// If the form is submitted, the code will be executed:
if ($submit) {
// Connect to the database
// (You may need to adjust the host name, user name and password)
MYSQL_CONNECT( "localhost", "root", "password");
mysql_select_db( "binary_data");
$data = addslashes(fread(fopen($form_data, "r"), filesize($form_data)));
$result=MYSQL_QUERY( "INSERT INTO binary_data ( description,bin_data,filename,filesize,filetype)
[Continue from the previous line:] VALUES ($form_description,$data,$form_data_name,$form_data_size,$form_data_type)");
$id= mysql_insert_id();
print "
This file has the following Database ID: $id";
MYSQL_CLOSE();
} else {
// Otherwise, display the form to store new data
?>
File Description:
File to upload/store in database:
}
?>
If you execute this program, you will see a simple Html form, click Browse to select a file, then click Submit.
When the file is uploaded to the web server, the program will tell you the ID of the file just uploaded. Remember this ID for use later.
An example program of how to access files
You can access the file you just saved through this program
// getdata.php3 - by Florian Dittmer
// Call Method: getdata.php3?id=
if($id) {
// You may need to adjust the hostname, username and password:
@MYSQL_CONNECT( "localhost", "root", "password" );
@mysql_select_db( "binary_data");
$query = "select bin_data,filetype from binary_data where id=$id";
$result = @MYSQL_QUERY($query);
$ data = @MYSQL_RESULT($result,0, "bin_data");
$type = @MYSQL_RESULT($result,0, "filetype");
Header( "Content-type: $type");
echo $data;
};
?>
The program must know which file to access, and you must pass the ID as a parameter.
For example: The ID of a file in the database is 2. You can call it like this:
getdata.php3?id=2
If you store the picture in the database, you can call it like calling the picture it.
Example: An image file has an ID of 3 in the database. You can call it like this:
How to store files larger than 1MB:
If you want to store files larger than 1MB, you must configure your program , PHP settings, SQL settings to make many modifications.
The following items may help you store files smaller than 24MB:
1. Modify store.php3 and change the value of MAX_FILE_SIZE to 24000000.
2. Modify your PHP settings. Under normal circumstances, PHP only allows files smaller than 2MB. You must change the value of max_filesize (in php.ini) to 24000000
3. Remove the MYSQL packet size limit. Under normal circumstances, MYSQL is less than 1 MB data packet.
4. You must restart your MYSQL with the following parameters
/usr/local/bin/safe_mysqld -O key_buffer=16M -O table_cache=128 -O sort_buffer =4M -O record_buffer=1M -O max_allowed_packet=24M
5. If the error still occurs:
It may be a timeout error. If you store a large file through a very slow connection, PHP's default time The limit is 30 seconds. You can change the value of max_execution_time (in php.ini) to -1
[Related recommendations]
2. Detailed explanation of how to write SQL statements to delete tables in different databases
3. Teach you how to use one machine to run multiple MySQL services
4. Small Mysql database backup script without virtual host
5. Detailed examples of using mysqldump to back up and restore tables
The above is the detailed content of Detailed explanation of examples of php storing images in mysql. For more information, please follow other related articles on the PHP Chinese website!

MySQLoffersvariousstorageengines,eachsuitedfordifferentusecases:1)InnoDBisidealforapplicationsneedingACIDcomplianceandhighconcurrency,supportingtransactionsandforeignkeys.2)MyISAMisbestforread-heavyworkloads,lackingtransactionsupport.3)Memoryengineis

Common security vulnerabilities in MySQL include SQL injection, weak passwords, improper permission configuration, and unupdated software. 1. SQL injection can be prevented by using preprocessing statements. 2. Weak passwords can be avoided by forcibly using strong password strategies. 3. Improper permission configuration can be resolved through regular review and adjustment of user permissions. 4. Unupdated software can be patched by regularly checking and updating the MySQL version.

Identifying slow queries in MySQL can be achieved by enabling slow query logs and setting thresholds. 1. Enable slow query logs and set thresholds. 2. View and analyze slow query log files, and use tools such as mysqldumpslow or pt-query-digest for in-depth analysis. 3. Optimizing slow queries can be achieved through index optimization, query rewriting and avoiding the use of SELECT*.

To monitor the health and performance of MySQL servers, you should pay attention to system health, performance metrics and query execution. 1) Monitor system health: Use top, htop or SHOWGLOBALSTATUS commands to view CPU, memory, disk I/O and network activities. 2) Track performance indicators: monitor key indicators such as query number per second, average query time and cache hit rate. 3) Ensure query execution optimization: Enable slow query logs, record and optimize queries whose execution time exceeds the set threshold.

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

MySQL uses a GPL license. 1) The GPL license allows the free use, modification and distribution of MySQL, but the modified distribution must comply with GPL. 2) Commercial licenses can avoid public modifications and are suitable for commercial applications that require confidentiality.

The situations when choosing InnoDB instead of MyISAM include: 1) transaction support, 2) high concurrency environment, 3) high data consistency; conversely, the situation when choosing MyISAM includes: 1) mainly read operations, 2) no transaction support is required. InnoDB is suitable for applications that require high data consistency and transaction processing, such as e-commerce platforms, while MyISAM is suitable for read-intensive and transaction-free applications such as blog systems.

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version
Useful JavaScript development tools
