我是靠谱客的博主 喜悦万宝路,最近开发中收集的这篇文章主要介绍php中的echo单引号_如何使用PHP在字符串中转义单引号(撇号),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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:

最后

以上就是喜悦万宝路为你收集整理的php中的echo单引号_如何使用PHP在字符串中转义单引号(撇号)的全部内容,希望文章能够帮你解决php中的echo单引号_如何使用PHP在字符串中转义单引号(撇号)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部