Overview
sql injection is to use the external interface of some databases to insert user data into the actual database operation language. In order to achieve the purpose of invading the database and even the operating system. In the security field, we should never trust user input. We must determine that the data entered by the user is unsafe, and we all need to filter the data entered by the user.
Without (runtime) compilation, there is no injection. So the way to fundamentally prevent the above types of attacks is to prevent data from being turned into code and be executed, and to always distinguish the boundaries between code and data. As for SQL injection specifically, the executed malicious code is compiled through the SQL interpretation engine of the database, so it only needs to prevent the data entered by the user from being compiled by the database system.
Unlike other databases,
MySQL can run in different SQL Modes (SQL server modes) and can apply different modes to different clients. This way each application can customize the server's operating mode according to its own needs. The schema defines which SQL syntax MySQL should support, and what kind of data validation checks should be performed. This is somewhat similar to apache configuring different levels of error logs, which errors are reported and which errors are not reported.
SQL injection
1. Injection example//php代码
$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('{$unsafe_variable}')");
When the code in the post is as follows: value'); DROP TABLE table;--
QueryThe code becomes
INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')This will directly
delete the table and your data will be destroyed.
2. Prevent sql injectionMethod 1prepareStatement+Bind-Variable: SQL statements and query parameters are sent to the database server for parsing respectively.
There are two implementation methods for php.
//使用PDO(PHP data object) $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute(array('name' => $name)); foreach ($stmt as $row) { // do something with $row } //使用mysql扩展-mysqli $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // do something with $row }
Method 2Escape the query statement (the most common way): use the conversion
function provided by the application. |Application|Function|
|--------| |MySQL C API | mysql_real_escape_string ()| |MySQL++|escape和quote修饰符| |PHP|使用mysql_real_escape_string()(适用于PHP4.3.0以前),之后可以使用mysqli或pdo| | Perl DBI|placeholder或quote()| |Ruby DBI|placeholder或quote()|
Method 3Use your own
define function for verification: its essence is still illegal for input Data is escaped and filtered. Input validation can be divided into: 1. Organize data to make it valid; 2. Reject known illegal input; 3. Only accept known legal input.
Method 4
Use stored procedures. For stored procedures, see: (9) Stored procedures and
custom functions in mysql
sql server mode
1.sql mode Syntax#查看当前sql模式
select @@sql_mode;
#查看当前sql模式
SELECT @@session.sql_mode;
#修改当前sql模式
SET [SESSION][GLOBAL] sql_mode='modes';
- The session option means that it will only take effect in this connection; and global means that it will not take effect in this connection and will take effect in the next connection.
- You can also use "--sql-mode='modes'" to set sql_mode when MySQL starts.
- can be set in the
config file.
2.sql_mode common valuesONLY_FULL_GROUP_BY:For GROUP BY
aggregation operation, if the column in SELECT is not in GROUP appears in BY, then this SQL is illegal because the column is not in the GROUP BY clause.
NO_AUTO_VALUE_ON_ZERO: This value affects the insertion of auto-growing columns. Under the default settings, inserting 0 or NULL represents generating the next auto-increasing value. This option is useful if the user wants to insert a value of 0 and the column is auto-increasing.
STRICT_TRANS_TABLES: In this mode, if a value cannot be inserted into a transaction table, the current operation will be interrupted, and there will be no limit on non-transaction tables.
NO_ZERO_IN_DATE: In strict mode, zero days and months are not allowed.
NO_ZERO_DATE: Set this value. MySQL database does not allow the insertion of zero dates. Inserting zero dates will throw an error instead of a warning.
ERROR_FOR_pISION_BY_ZERO: During the INSERT or UPDATE process, if the data is divided by zero, an error is generated instead of a warning. If the mode is not given, MySQL returns NULL when the data is divided by zero.
NO_AUTO_CREATE_USER: Prohibits GRANT from creating users with empty passwords.
NO_ENGINE_SUBSTITUTION: Throw an error if the required storage engine is disabled or not compiled. When this value is not set, the default storage engine is used instead and an exception is thrown.
PIPES_AS_CONCAT:
Treat "||" as a concatenation of strings operators instead of or operators , which is the same as the Oracle database, and is similar to the string concatenation function Concat.
ANSI_QUOTES:
With ANSI_QUOTES enabled, you cannot quote a string with double quotes because it is interpreted as an identifier.
Description
ORACLE's sql_mode setting is equivalent to: PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS, NO_TABLE_OPTIONS, NO_FIELD_OPTIONS, NO_AUTO_CREATE_USER.
【Related recommendations】
1. Free mysql online video tutorial
2. MySQL latest manual tutorial
3. Boolean Education Yan Shiba mysql introductory video tutorial
The above is the detailed content of SQL injection examples and how to prevent SQL injection. For more information, please follow other related articles on the PHP Chinese website!

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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),

Notepad++7.3.1
Easy-to-use and free code editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
