MySQL Interview Summary

SQL injection

The so-called SQL injection is to deceive the server to execute malicious SQL commands by inserting SQL commands into the web form to submit or input the query string of the domain name or page request.

We should never trust user input, we must assume that user input data is unsafe, and we all need to filter user input data.

In the following example, the entered username must be a combination of letters, numbers, and underscores, and the username must be between 8 and 20 characters long:

if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches)){
   $result = mysqli_query($conn, "SELECT * FROM users 
                          WHERE username=$matches[0]");
} else {
   echo "username 输入异常";
}

Let's take a look at the SQL situation that occurs when no special characters are filtered:

// 设定$name 中插入了我们不需要的SQL语句
$name = "Qadir'; DELETE FROM users;";
 mysqli_query($conn, "SELECT * FROM users WHERE name='{$name}'");

In the above injection statement, we did not filter the variable of $name. The SQL statement that we do not need is inserted into $name, which will delete all the data in the users table.

mysqli_query() in PHP is not allowed to execute multiple SQL statements, but SQLite and PostgreSQL can execute multiple SQL statements at the same time, so we need to strictly verify the data of these users.

To prevent SQL injection, we need to pay attention to the following points:

  1. Never trust user input. Validate the user's input, you can use regular expressions, or limit the length; convert single quotes and double "-", etc.
  2. Never use dynamic assembly sql, you can use parameterized sql or directly use stored procedures for data query and access.
  3. Never use a database connection with administrator privileges, use a separate database connection with limited privileges for each application.
  4. Do not store confidential information directly, encrypt or hash passwords and sensitive information.
  5. The exception information of the application should give as few hints as possible, and it is best to wrap the original error message with a custom error message
  6. The detection method of SQL injection is generally detected by auxiliary software or website platform. The software generally uses the SQL injection detection tool jsky, and the website platform has the Yisi website security platform detection tool. MDCSOFT SCAN et al. Using MDCSOFT-IPS can effectively defend against SQL injection, XSS attacks, etc.

Prevent SQL Injection

In scripting languages ​​such as Perl and PHP you can escape the data entered by the user to prevent SQL injection.

The MySQL extension for PHP provides the mysqli_real_escape_string() function to escape special input characters.

if (get_magic_quotes_gpc()) {
  $name = stripslashes($name);
}
$name = mysqli_real_escape_string($conn, $name);
 mysqli_query($conn, "SELECT * FROM users WHERE name='{$name}'");

Injection in Like Statements

When querying like, if the values ​​entered by the user include "_" and "%", this situation will occur: the user only wants to query "abcd_", but the query results contain "abcd_", "abcde", "abcdf" And so on; problems also arise when users want to query "30%" (note: 30%).

In a PHP script we can use the addcslashes() function to handle the above situation, as in the following example:

$sub = addcslashes(mysqli_real_escape_string($conn, "%something_"), "%_");
// $sub == \%something\_
 mysqli_query($conn, "SELECT * FROM messages WHERE subject LIKE '{$sub}%'");

The addcslashes() function adds a backslash before the specified character.

Syntax format:

addcslashes(string,characters)
parameter describe
string Required. Specifies the string to check.
characters Optional. Specifies the character or range of characters affected by addcslashes().

For specific applications, see: PHP addcslashes() function

Check out: http://www.runoob.com/mysql/mysql-sql-injection.html

The difference between myisam and innodb in MySQL

(1), different;

  1. InnoDB supports things while MyISAM does not
  2. InnoDB supports row-level locking, while MyISAM supports table-level locking
  3. InnoDB supports MVCC, while MyISAM does not
  4. InnoDB supports foreign keys, while MyISAM does not
  5. InnoDB does not support full text indexing, while MyISAM does.

(2), 4 major features of the innodb engine

Insert buffer (insert buffer), double write (double write), adaptive hash index (ahi), read ahead (read ahead)

(3) Which of the 2 is faster and why select count(*)

myisam is faster because myisam internally maintains a counter that can be called directly.

Database optimization ideas

1. SQL statement optimization

  1. You should try to avoid using the != or <> operator in the where clause, otherwise the engine will give up using the index and perform a full table scan.
  2. You should try to avoid the null value judgment of the field in the where clause, otherwise the engine will give up the use of the index and perform a full table scan, such as: select id from t where num is null , you can set the default value of 0 on num to ensure that the table There is no null value in the num column , and then query like this: select id from t where num=0
  3. Many times using exists instead of in is a good choice
  4. Replace the HAVING clause with a Where clause because HAVING will only filter the result set after all records have been retrieved

2. Index optimization

3. Database structure optimization

1) Paradigm optimization: such as eliminating redundancy (saving space..)

2) Anti-paradigm optimization: such as adding redundancy appropriately (reducing joins)

3) Split table: Partition separates data physically, and data of different partitions can be stored in data files on different disks. In this way, when querying this table, you only need to scan in the table partition instead of a full table scan, which significantly shortens the query time. In addition, partitions on different disks will also spread the data transmission of this table in different Disk I/O, a carefully set partition can evenly spread the data transfer competition for disk I/O. This method can be used for timetables with a large amount of data. Automatically create table partitions by month.

4) Splitting is actually divided into vertical splitting and horizontal splitting: Case: The simple shopping system temporarily involves the following table:

  1. Product table (data volume 10w, stable)
  2. Order table (data volume is 200w, and there is a growing trend)
  3. User table (data volume is 100w, and there is a growing trend) Take mysql as an example to describe horizontal splitting and vertical splitting. The order of magnitude that mysql can tolerate is millions of static data can reach tens of millions of  vertical splits: problem solving: table and table The io competition between them does not solve the problem: the pressure of the increase in the amount of data in a single table The solution: put the product table and the user table on one server and the order table on a separate server  Horizontal split:  solve the problem: data in a single table The pressure of volume growth does not solve the problem: io contention between tables

Scenario: User table is split into male user table and female user table by gender, order table is split into completed order and unfinished order by completed and completed order, product table is not completed order, and completed order table box is placed on a server for male user Put the table on a server and put the female user table on a server

type of data

It can be roughly divided into three categories: numeric, date/time and string (character) types.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324534288&siteId=291194637
Recommended