前言
本文主要給大家介紹了關(guān)于mysql語句插入含單引號(hào)或反斜杠值的相關(guān)內(nèi)容,下面話不多說了,來一起看看詳細(xì)的介紹吧
比如說有個(gè)表,它的結(jié)構(gòu)是這個(gè)樣子的
CREATE TABLE `activity` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `title` varchar(255) NOT NULL COMMENT '活動(dòng)標(biāo)題', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='活動(dòng)表';
比如說往里面插入記錄,示例代碼如下:
$servername = "xxxxservername"; $port = 3306; $username = "xxxusername"; $password = "xxxpwd"; $dbname = "xxxxxxdb"; // 創(chuàng)建連接 $conn = new mysqli($servername, $username, $password, $dbname, 8306); // 檢測連接 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();
這一段代碼執(zhí)行OK,沒啥問題。但是如果代碼里面的title變成happy valentine's day!就會(huì)報(bào)如下錯(cuò)誤,提示你有語法錯(cuò)誤:
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
因?yàn)?code>INSERT INTO activity (title) VALUES ( 'happy valentine's day!');這個(gè)sql語句里面單引號(hào)不是成對(duì)的。
有時(shí)候會(huì)往數(shù)據(jù)庫里面插入一些用戶給的數(shù)據(jù),很可能會(huì)出現(xiàn)上面這種情況,那么該如何避免呢?
要對(duì)sql里面的特殊字符進(jìn)行轉(zhuǎn)義。可以把$sql的那一行代碼改成如下這樣:
$sql = sprintf("INSERT INTO activity (title) VALUES ( '%s');", mysqli_real_escape_string($conn, $item['title']));
整個(gè)sql字符串實(shí)際上是這樣的:
INSERT INTO activity (title) VALUES ( 'happy valentine\'s day!');"
有時(shí)候還會(huì)出現(xiàn)一種問題: json_encode之后,里面的中文被轉(zhuǎn)成unicode碼,插入到mysql里面發(fā)現(xiàn)\被吃掉了。
比如說中文這兩個(gè)字的unicode碼是\u4e2d\u6587,但是有時(shí)候插到數(shù)據(jù)庫里反斜杠被吃掉了變成了u4e2du6587
看如下示例代碼:
$item['title'] = json_encode([ 'balbalbla' => '中文' ]); $sql = sprintf("INSERT INTO activity (title) VALUES ( '%s');", $item['title']);
整個(gè)sql字符串實(shí)際上是這樣的:
INSERT INTO activity (title) VALUES ( '{"balbalbla":"u4e2du6587"}');
插入到數(shù)據(jù)庫里面,title這個(gè)字段的值就變成了{"balbalbla":"u4e2du6587"}
。
那是因?yàn)檫@里的\被當(dāng)成轉(zhuǎn)義符了,實(shí)際上要對(duì)unicode碼的\再次轉(zhuǎn)義,這樣插入數(shù)據(jù)庫的才是對(duì)的
$item['title'] = json_encode([ 'balbalbla' => '中文' ]); $sql = sprintf("INSERT INTO activity (title) VALUES ( '%s');", mysqli_real_escape_string($conn, $item['title']));
整個(gè)sql字符串實(shí)際上是這樣的:
INSERT INTO activity (title) VALUES ( '{\"balbalbla\":\"\\u4e2d\\u6587\"}');
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
標(biāo)簽:吐魯番 安徽 葫蘆島 拉薩 洛陽 嘉峪關(guān) 甘南
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《mysql語句如何插入含單引號(hào)或反斜杠的值詳解》,本文關(guān)鍵詞 mysql,語句,如何,插入,含單,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。