When PHP connects to the database, it may be necessary to add quotation marks to the strings in the SQL
statement. In order to solve this problem, we can use PHP's built-in functionsquote()
function, this article will take you to take a look.
First let’s take a look at the syntax of the quote()
function:
public PDO::quote ( string $string , int $parameter_type = PDO::PARAM_STR ) : string
$string: The string to which quotation marks are to be added.
$parameter_type: Prompt the data type for the driver to choose the quotation mark style.
Return value: Returns a quoted string, which can theoretically be safely used in SQL
statements. If the driver does not support this method, false
will be returned.
Code example:
1. Add quotation marks to ordinary strings
<?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 Dangerous strings in quotes
<?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'
Recommended: 《2021 PHP Interview Questions Summary (Collection) 》《php video tutorial》
The above is the detailed content of Detailed explanation of PDO::quote in PHP (with code examples). For more information, please follow other related articles on the PHP Chinese website!