PDO使用%和concat准备语句

时间:2016-05-09 05:04:19

标签: php mysql pdo

我正在将PHP中的一些MySQL查询转换为PDO预处理语句查询。

大多数查询都很简单,但我遇到了几个问题而且我不确定它们应该如何看待

在我转换的常规查询中:

where field ='$type'

进入

where field =:type

并改变

$results->execute();

$结果 - >执行(阵列('类型' = GT; $型));

情景1

通常在转换它们时,变量变为:在查询中键入,但使用%它会变为:键入%或:键入'%'

where field like '$type%'

场景2

使用concat时

concat(uuid(),'-$id')

这应该如何处理?当变量前面有 - 时,如何处理?

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

您需要了解的是a placeholder have to represent a complete data literal only

因此您的代码将是:

情景1

在PHP中创建一个带通配符的搜索字符串,

$type = "$type%";

然后你可以用通常的方式绑定它。

场景2

只需为CONCAT()添加一个参数:

concat(uuid(),'-', :id)

答案 1 :(得分:-2)

在情景1中你应该和简单的一样

$pdo = new PDO("mysql:host=localhost;dbname=database;","root","");
$smt = $pdo->prepare("...... WHERE col=:type");

Scenarion 1:

$smt->bindParam(":type", $type . '%' , PDO::PARAM_STRING);

Scenarion 2:

$smt->bindParam(":type", concat(uuid(),"-$id") , PDO::PARAM_STRING);

之后你就执行并做自己的事情了:

$smt->execute();