php - 如何使用 php 转义字符串中的单引号(撇号)

标签 php mysql pdo

我有一个像这样的 SQL 查询:-

$stmt = $pdo->prepare(
   "SELECT * FROM `products_keywords` WHERE `product_type` = '" . $product_type . "' ");

我不知道 $product_type 变量的值是多少。但是现在,我在 $product_type 变量中得到了 Men's Shirt,这导致了我的 SQL 查询中的语法错误。我确信此错误是由于 Men's Shirt 值中的单引号引起的。我如何根据我的查询转义这个值?以及如何检查我的 $product_type 变量中是否有单引号,然后根据我的查询对其进行转义。提前致谢。

最佳答案

答案是您不需要。 PDO 的 prepare 的正确使用方法是这样的:

$stmt = $pdo->prepare(
   "SELECT * FROM `products_keywords` WHERE `product_type` = ?");

这就是使用准备好的语句的全部要点。那你bind参数如下:

$stmt->bindParam(1, $product_type)

证明,

架构:

create table `products_keywords`
(   `id` int not null,
    `products_keywords` varchar(1000) not null,
    `product_type` varchar(100) not null
);
insert `products_keywords` (`id`,`products_keywords`,`product_type`) values  
(1,'zoom lawn cut mower',"Lawn Mower"),
(2,'stylish torso Polo','Men\'s Shirt');

查看数据:

select * from `products_keywords`;
+----+---------------------+--------------+
| id | products_keywords   | product_type |
+----+---------------------+--------------+
|  1 | zoom lawn cut mower | Lawn Mower   |
|  2 | stylish torso Polo  | Men's Shirt  |
+----+---------------------+--------------+

PHP:

<?php
    // turn on error reporting, or wonder why nothing is happening at times
    error_reporting(E_ALL);
    ini_set("display_errors", 1);    

    $servername="localhost";
    $dbname="so_gibberish";
    $username="nate123";
    $password="openSesame1";

    try {
        $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        $product_type="Men's Shirt";
        $stmt = $pdo->prepare("SELECT * FROM `products_keywords` WHERE `product_type` = ?");
        $stmt->bindParam(1, $product_type);
        $stmt->execute();
        while($row = $stmt->fetch()) {
            echo $row['id'].", ".$row['products_keywords'].", ".$row['product_type']."<br/>";
        }
    } catch (PDOException $e) {
        echo 'pdo problemo: ' . $e->getMessage();   // dev not production code
        exit();
    }
?>

浏览器:

enter image description here

关于php - 如何使用 php 转义字符串中的单引号(撇号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39634968/

相关文章:

php pdo函数连接到数据库并进行查询

php - 为什么是 stdClass 命名空间?

mysql - SequelizeJS - hasMany 到具有连接表的同一个表上的 hasMany

mysql - 有没有办法加快这个mysql?

mysql - 查询中有LIMIT时,如何获取总结果数?

mysql - 奇怪的SQL结果order by date, count(date)

php - SQL Server 定期固定延迟

php - 在 PHP 中执行 "foreach x except y"最优雅的方法是什么?

php preg_match 验证价格格式

php - MySQL 中使用 PHP undefined variable 的 CONCAT 函数