日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql 查询的转义字符_mysql – 如何在LIKE查询中转义字符?

發(fā)布時間:2024/4/13 数据库 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql 查询的转义字符_mysql – 如何在LIKE查询中转义字符? 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

MySQL Manual開始:

Because MySQL uses C escape syntax in strings (for example, “\n” to represent a newline character), you must double any “\” that you use in LIKE strings. For example, to search for “\n”, specify it as “\\n”. To search for “\”, specify it as “\\\\”; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.

因此,您應(yīng)該分兩步為LIKE運算符轉(zhuǎn)義字符串.

在PHP中它可以是這樣的:

// Your search string, for example, from POST field

$string = $_POST['column'];

// First step - LIKE escaping

$string = str_replace(array('\\', '_', '%'), array('\\\\', '\\_', '\\%'), $string);

// Second step - literal escaping

$string = mysql_real_escape_string($string);

// Result query

mysql_query("SELECT * FROM `table` WHERE `column` LIKE '%".$string."%'");

更新:

MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

使用MySQLi

// Connect to database

$mysqli = new mysqli('localhost', 'username', 'password', 'database');

// Your search string, for example, from POST field

$string = $_POST['column'];

// First step - LIKE escaping

$string = str_replace(['\\', '_', '%'], ['\\\\', '\\_', '\\%'], $string);

// Second step - literal escaping

$string = $mysqli->real_escape_string($string);

// Result query

$mysqli->query("SELECT * FROM `table` WHERE `column` LIKE '%{$string}%'");

使用PDO

// Connect to database

$conn = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Your search string, for example, from POST field

$string = $_POST['column'];

// First step - LIKE escaping

$string = str_replace(['\\', '_', '%'], ['\\\\', '\\_', '\\%'], $string);

// Second step - literal escaping

$string = $conn->quote($string);

// Result query

$conn->query("SELECT * FROM `table` WHERE `column` LIKE '%{$string}%'");

或者您可以使用PDO預(yù)處理語句,而不是第二步(文字轉(zhuǎn)義):

// Connect to database

$conn = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Your search string, for example, from POST field

$string = $_POST['column'];

// First step - LIKE escaping

$string = str_replace(['\\', '_', '%'], ['\\\\', '\\_', '\\%'], $string);

// Prepare a statement for execution

$statement = $conn->prepare("SELECT * FROM `table` WHERE `column` LIKE ?");

// Execute a prepared statement

$statement->execute(["%{$string}%"]);

總結(jié)

以上是生活随笔為你收集整理的mysql 查询的转义字符_mysql – 如何在LIKE查询中转义字符?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。