函數(shù)名: db2_escape_string()
適用版本: PHP 5, PHP 7
用法: string db2_escape_string ( resource $connection , string $string_literal )
該函數(shù)用于在DB2數(shù)據(jù)庫(kù)連接中轉(zhuǎn)義字符串,以防止SQL注入攻擊。它返回一個(gè)轉(zhuǎn)義后的字符串。
參數(shù):
$connection
: DB2數(shù)據(jù)庫(kù)連接資源。$string_literal
: 需要進(jìn)行轉(zhuǎn)義的字符串。
示例:
<?php
// 創(chuàng)建DB2數(shù)據(jù)庫(kù)連接
$connection = db2_connect("dbname", "username", "password");
if ($connection) {
$string = "It's a test string.";
$escaped_string = db2_escape_string($connection, $string);
echo "轉(zhuǎn)義前的字符串: " . $string . "<br>";
echo "轉(zhuǎn)義后的字符串: " . $escaped_string;
// 輸出: 轉(zhuǎn)義前的字符串: It's a test string.
// 轉(zhuǎn)義后的字符串: It''s a test string.
// 執(zhí)行數(shù)據(jù)庫(kù)查詢時(shí)使用轉(zhuǎn)義后的字符串
$sql = "SELECT * FROM table WHERE field = '" . $escaped_string . "'";
$result = db2_exec($connection, $sql);
// ...
db2_close($connection);
}
?>
上述示例中,首先使用db2_connect()函數(shù)創(chuàng)建了一個(gè)DB2數(shù)據(jù)庫(kù)連接,然后使用db2_escape_string()函數(shù)對(duì)字符串進(jìn)行轉(zhuǎn)義,存儲(chǔ)在$escaped_string
變量中。之后可以將轉(zhuǎn)義后的字符串用于構(gòu)建SQL查詢語(yǔ)句,以防止SQL注入攻擊。最后使用db2_close()函數(shù)關(guān)閉數(shù)據(jù)庫(kù)連接。