How to insert a value containing single quotes or backslashes in MySQL statements

How to insert a value containing single quotes or backslashes in MySQL statements

Preface

This article mainly introduces the relevant content about MySQL statements inserting values ​​containing single quotes or backslashes. Let's take a look at the detailed introduction.

For example, there is a table whose structure is like this

CREATE TABLE `activity` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
 `title` varchar(255) NOT NULL COMMENT 'Activity title',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Activity table';

For example, to insert a record into it, the sample code is as follows:

$servername = "xxxxservername";
$port = 3306;
$username = "xxxusername";
$password = "xxxpwd";
$dbname = "xxxxxxdb";

// Create a connection $conn = new mysqli($servername, $username, $password, $dbname, 8306);

// Check connection if ($conn->connect_error) {
 die("connect failed: " . $conn->connect_error);
}

$item['title'] = 'happy new year!';
$sql = sprintf("INSERT INTO activity (title) VALUES ( '%s');", $item['title']);
var_dump($sql);
if ($conn->query($sql) === TRUE) {
	echo "insert success\n";
} else {
 echo "insert failed:" . $conn->error;
}

$conn->close();

This code executes OK, no problem. But if the title in the code becomes happy valentine's day!, the following error will be reported, indicating that you have a syntax error:

insert failed:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's day!')' at line

Because the single quotes in the SQL statement INSERT INTO activity (title) VALUES ( 'happy valentine's day!'); are not paired.

Sometimes we insert some user-given data into the database, and the above situation is likely to occur. So how can we avoid it?

You need to escape the special characters in sql. You can change the $sql line of code to the following:

$sql = sprintf("INSERT INTO activity (title) VALUES ( '%s');", mysqli_real_escape_string($conn, $item['title']));

The entire sql string actually looks like this:

INSERT INTO activity (title) VALUES ( 'happy valentine\'s day!');"

Sometimes there is a problem: after json_encode, the Chinese characters in it are converted into unicode code, and when inserted into mysql, it is found that \ is eaten.

For example, the unicode code of the two Chinese characters is \u4e2d\u6587, but sometimes when inserted into the database, the backslash is eaten up and becomes u4e2du6587

See the following sample code:

$item['title'] = json_encode([
  'balbalbla' => 'Chinese'
]);
$sql = sprintf("INSERT INTO activity (title) VALUES ( '%s');", $item['title']);

The entire sql string actually looks like this:

INSERT INTO activity (title) VALUES ( '{"balbalbla":"\u4e2d\u6587"}');

When inserted into the database, the value of the title field becomes {"balbalbla":"u4e2du6587"} .

That's because the \ here is used as an escape character. In fact, the unicode code \ must be escaped again so that it can be inserted into the database correctly.

$item['title'] = json_encode([
  'balbalbla' => 'Chinese'
]);
$sql = sprintf("INSERT INTO activity (title) VALUES ( '%s');", mysqli_real_escape_string($conn, $item['title']));

The entire sql string actually looks like this:

INSERT INTO activity (title) VALUES ( '{\"balbalbla\":\"\\u4e2d\\u6587\"}');

Summarize

The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support for 123WORDPRESS.COM.

You may also be interested in:
  • Problems with using multiple single quotes and triple quotes in MySQL concat
  • A detailed analysis of the murder caused by a misplaced double quote in MySQL
  • About Mysql query with single quotes and inserting strings with single quotes
  • Analysis of MYSQL performance issues caused by a single quote
  • Detailed explanation of the difference and usage of quotes and backticks in MySQL

<<:  Detailed steps to change the default password when installing MySQL in Ubuntu

>>:  How to simply encapsulate axios in vue

Recommend

vue uses Ele.me UI to imitate the filtering function of teambition

Table of contents Problem Description The general...

How to quickly clean up billions of data in MySQL database

Today I received a disk alarm exception. The 50G ...

MySQL insert json problem

MySQL 5.7.8 and later began to support a native J...

CSS style reset and clear (to make different browsers display the same effect)

In order to make the page display consistent betwe...

Life cycle and hook functions in Vue

Table of contents 1. What is the life cycle 2. Th...

HTML uncommon tags optgroup, sub, sup and bdo example code

Optgroup is used in the select tag to make the dro...

Implementation of deploying Apollo configuration center using docker in CentOS7

Apollo open source address: https://github.com/ct...

Detailed explanation of the process of building and running Docker containers

Simply pull the image, create a container and run...

Sharing of experience on repairing MySQL innodb exceptions

A set of MySQL libraries for testing. The previou...

vue+element custom query component

This article mainly introduces the Vue project. O...

Solution to overflow of html table

If the table is wide, it may overflow. For exampl...