PHP在連接數據庫時,可能需要為SQL語句中的字符串添加引號,為了解決這一問題,我們可以使用PHP的內置函數quote()函數,本文就帶大家來看一看。
首先來看一看quote()函數的語法:
public PDO::quote ( string $string , int $parameter_type = PDO::PARAM_STR ) : string
$string:要添加引號的字符串。
$parameter_type:為驅動提示數據類型,以便選擇引號風格。
返回值:返回加引號的字符串,理論上可以安全用于 SQL 語句。 如果驅動不支持這種方式,將返回 false 。
代碼實例:
1、普通字符串加引號
<?php $servername = "localhost"; $username = "root"; $password = "root123456"; $dbname = "my_database"; try { $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); echo "連接成功"."<br>"; // $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); $string = 'Nice'; print "Unquoted string: $string"; echo "<br>"; print "Quoted string: " . $pdo->quote($string) . "\n"; }catch(PDOException $e){ echo $e->getMessage(); }
輸出:連接成功
Unquoted string: Nice Quoted string: 'Nice'
2、危險字符串加引號
<?php $servername = "localhost"; $username = "root"; $password = "root123456"; $dbname = "my_database"; try { $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); echo "連接成功"."<br>"; // $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); $string = 'Naughty \' string'; print "Unquoted string: $string"; echo "<br>"; print "Quoted string:" . $pdo->quote($string); }
輸出:連接成功
Unquoted string: Naughty ' string Quoted string:'Naughty \' string'