Home  >  Article  >  Backend Development  >  Detailed explanation of PDO::quote in PHP (with code examples)

Detailed explanation of PDO::quote in PHP (with code examples)

autoload
autoloadOriginal
2021-04-25 13:10:132285browse

Detailed explanation of PDO::quote in PHP (with code examples)

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 = &#39;Nice&#39;;
    print "Unquoted string: $string";
    echo "<br>";
    print "Quoted string: " . $pdo->quote($string) . "\n";
}catch(PDOException $e){
    echo $e->getMessage();
}
输出:连接成功
    Unquoted string: Nice
    Quoted string: &#39;Nice&#39;

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 = &#39;Naughty \&#39; string&#39;;
    print "Unquoted string: $string";
    echo "<br>";
    print "Quoted string:" . $pdo->quote($string);
    }
输出:连接成功
Unquoted string: Naughty &#39; string
Quoted string:&#39;Naughty \&#39; string&#39;

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn