php - 具有绑定参数的 PHP 变化查询。pgSQL VS MySQL 准备好的语句 | ?,?,? 对比 1 美元、2 美元、3 美元
问题描述
在 MySQL 中,您可以使用?
绑定语句中的每个变量,这样做的好处是SQL
字符串不关心变量在语句中绑定的顺序。在pgSQL
我发现变量必须有一个$(number) - (e.g. $1,$2,$3)
. 这使得该语句不灵活,并要求该语句具有所有变量,否则$2
将成为$1
如果它丢失。
例子:
Table: apples
| apple_id | name | color | cost |
----------------------------------
| 1 | A | red | 1.50 |
| 2 | A | red | 1.60 |
| 3 | C | red | 1.70 |
| 4 | D | blue | 1.80 |
| 5 | D | blue | 2.50 |
| 6 | F | gold | 3.50 |
| 7 | G | green | 4.50 |
| 8 | H | green | 5.50 |
------------------------------------
//MySQL Version
//COMING FROM CLIENT | MAY BE NULL IF FILTER NOT SET
$color = "";
$name = "";
$vars = 0;
$and = "";
if(!empty($_POST['color']){
$color = "color = ?";
$vars++;
}
if(!empty($_POST['name']){
$name = "name = ?";
$vars++;
}
if($vars > 1){
$and = "and";
}
$sql = "SELECT apple_id,name,color,cost FROM apples WHERE ".$color." ".$and." ".$name.""
$stmt = $conn->prepare($sql);
if(!empty($_POST['color']) && !empty($_POST['name'])){
$stmt->bind_param('ss', $_POST['color'],$_POST['name']);
}elseif(!empty($_POST['color'])){
//color can be position 1
$stmt->bind_param('s',$_POST['color']);
}elseif(!empty($_POST['name'])){
//name can be position 1
$stmt->bind_param('s', $_POST['name']);
}
$stmt->execute();
$stmt->bind_result($id,$name,$color,$cost);
while($stmt->fetch()){
//blah blah
}
pgSQL
$color = "";
$name = "";
$vars = 0;
$and = "";
if(!empty($_POST['color']){
$color = "color = $1";
$vars++;
}
if(!empty($_POST['name']){
$name = "name = $2";
$vars++;
}
if($vars > 1){
$and = "and";
}
$sql = "SELECT apple_id,name,color,cost FROM apples WHERE ".$color." ".$and." ".$name.""
$result = pg_prepare($conn, 'query' ,$sql);
if(!empty($_POST['color']) && !empty($_POST['name'])){
//this works if both filters are set.
$result = pg_execute($conn,'query' , array($_POST['color'],$_POST['name']));
}elseif(!empty($_POST['color'])){
//this works if only color is set
$result = pg_execute($conn,'query' , array($_POST['color']));
}elseif(!empty($_POST['name'])){
//this fails
$result = pg_execute($conn,'query' , array($_POST['name']));
}
while($assoc = pg_fetch_assoc($result)){
//blah blah
}
我意识到我可以通过努力查看哪些变量以前不是空的,并帮助$_POST['name']
确定$1
它是否是唯一的,但这是一个非常简单的例子。我还有其他有 4 个变量的示例。
有没有更简单的方法来做到这一点?或者更灵活的方式来绑定变量?
解决方案
推荐阅读
- .htaccess - 将“子文件夹”重定向到新 URL;Joomla 和 .htaccess
- javascript - React Native 后台计时器永不停止
- sql - 将 2 个表合并为 1 个(SQL Server)的最佳方法是什么,只有一个共同的日期时间类型的列
- postgresql - 复制数据或将数据从 CSV 导入 PostgreSQL 时出错
- python - 将列表与 CSV 文件进行比较
- python - Value_counts 未返回所需的输出
- php - 访问部署在共享主机上的公共目录 laravel 5.5
- javascript - Vue:如何在 mapFields 中使用组件道具
- python-3.x - 从 Target 抓取产品和商店信息
- linux-mint - 如何在 Linux Mint 中正确构建 RTEMS 4.11 环境