php中的echo单引号_如何使用PHP在字符串中转义单引号(撇号)

博客讨论了在PHP中如何使用PDO预处理语句来避免SQL注入问题。文章通过示例展示了如何正确地准备和绑定参数,特别是在产品类型包含特殊字符如单引号时。作者强调了预处理语句的重要性,因为它可以确保即使变量值包含可能破坏查询的字符,也能安全执行。
摘要由CSDN通过智能技术生成

I have a SQL query like this:-

$stmt = $pdo->prepare(

"SELECT * FROM `products_keywords` WHERE `product_type` = '" . $product_type . "' ");

I don't know what will be the value in the $product_type variable. But Now, I am getting Men's Shirt in $product_type variable which is causing the syntax error in my SQL query. I am sure this error is due to the single quote in Men's Shirt value. How I escape this value according to my query? And how to check if there is single quote in my $product_type variable and then escape it according to my query. Thanks in advance.

解决方案

The answer is that you don't need to. The proper way to use PDO's prepare is like this:

$stmt = $pdo->prepare(

"SELECT * FROM `products_keywords` WHERE `product_type` = ?");

This is the whole point of using a prepared statement. Then you bind the parameter as follows:

$stmt->bindParam(1, $product_type)

Proof,

Schema:

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');

View data:

select * from `products_keywords`;

+----+---------------------+--------------+

| id | products_keywords | product_type |

+----+---------------------+--------------+

| 1 | zoom lawn cut mower | Lawn Mower |

| 2 | stylish torso Polo | Men's Shirt |

+----+---------------------+--------------+

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']."
";

}

} catch (PDOException $e) {

echo 'pdo problemo: ' . $e->getMessage(); // dev not production code

exit();

}

?>

Browser:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值