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

Angular Dependency Injection Explained

Table of contents Overview 1. Dependency Injectio...

Record the steps of using mqtt server to realize instant communication in vue

MQTT Protocol MQTT (Message Queuing Telemetry Tra...

In-depth understanding of the use of CSS clear:both

clear:both is used to清除浮動This is the impression I...

MySQL master-slave replication delay causes and solutions

Table of contents A brief overview of the replica...

PHP scheduled backup MySQL and mysqldump syntax parameters detailed

First, let's introduce several common operati...

MySQL 8.X installation tutorial under Windows

I had been using MySQL 5.7 before, but because My...

Guide to using env in vue cli

Table of contents Preface Introduction-Official E...

Example of how to install nginx to a specified directory

Due to company requirements, two nginx servers in...

Key issues and solutions for web page access speed

<br /> The website access speed can directly...

The easiest way to debug stored procedures in Mysql

A colleague once told me to use a temporary table...

Detailed steps to install Nginx on Linux

1. Nginx installation steps 1.1 Official website ...

In-depth analysis of MySQL execution plans

Preface In the previous interview process, when a...

JS uses canvas technology to imitate echarts bar chart

Canvas is a new tag in HTML5. You can use js to o...