我一直在尝试使用Mysqli准备的陈述整天一起获得概念证明由于我的查询的动态性质,需要它们。
幕后的形式就像:http://pasteboard.co/k6h0cvq.png-您也可以在此处了解该概念。我的查询是不返回的结果或错误,只是一个警告Array to string conversion
,它在绑定值时发生。
我还担心我对值的绑定不起作用,我不能将它们放在foreach循环中,因为它不能在调用$stmt
变量之前位于foreach循环中,否则会丢弃更多错误。
我一直在阅读文档并观看教程,但是我找不到任何显示如何在查询中实现模型的东西。
我希望我足够清楚,这是一项令人沮丧的努力,试图让我围绕PDO和一般准备的陈述。
任何帮助都是多大的感谢。谢谢!
php
if (isset($_POST['platform'], $_POST['bandwidth'], $_POST['price'])){
$platform = $_POST['platform'];
$bandwidth = $_POST['bandwidth'];
$price = $_POST['price'];
$query = "SELECT * FROM 'hosts' WHERE";
foreach($platform as $platform) {
$query .= " 'platform' LIKE %:platform% OR";
}
$query = substr($query, 0, -2);
foreach($bandwidth as $bandwidth) {
$query .= " AND 'bandwidth' BETWEEN :bandwidth OR";
}
$query = substr($query, 0, -2);
foreach($price as $price) {
$query .= " AND 'price' BETWEEN :price OR";
}
$query = substr($query, 0, -2);
$conn = new PDO('mysql:host=127.0.0.1; dbname=test', 'root', '');
$stmt = $conn->prepare($query);
if ($_POST['platform']){
$stmt->bindValue(':platform', $_POST['platform']);
}
if ($_POST['bandwidth']){
$stmt->bindValue(':bandwidth', $_POST['bandwidth']);
}
if ($_POST['price']){
$stmt->bindValue(':price', $_POST['price']);
}
$stmt->execute();
foreach($stmt as $row) {
print_r($row);
}
}
这是您代码的重写。我使用数组来构建嵌套的AND
和OR
条件,使用implode
将它们组合起来,而不是字符串串联序列。我使用阵列索引给每个占位符一个不同的名称。我将您所有的BETWEEN
条款更改为=
,因为BETWEEN
需要两个参数,即范围的开始和结尾。
if (isset($_POST['platform'], $_POST['bandwidth'], $_POST['price'])){
$platform = $_POST['platform'];
$bandwidth = $_POST['bandwidth'];
$price = $_POST['price'];
$query = "SELECT * FROM hosts";
$ands = array();
$bind_array = array();
$ors = array();
foreach($platform as $i => $platform) {
$ors[] = "platform LIKE CONCAT('%', :platform{$i}, '%')";
$bind_array[":platform{$i}"] = $platform;
}
if ($ors) {
$ands[] = "(" . implode(" OR ", $ors) . ")";
}
$ors = array();
foreach($bandwidth as $i => $bandwidth) {
$ors[] = "bandwidth = :bandwidth{$i}";
$bind_array[":bandwidth{$i}"] = $bandwidth;
}
if ($ors) {
$ands[] = "(" . implode(" OR ", $ors) . ")";
}
$ors = array();
foreach($price as $i => $price) {
$ors[] = "price = :price{$i}";
$bind_array[":price{$i}"] = $price;
}
if ($ors) {
$ands[] = "(" . implode(" OR ", $ors) . ")";
}
if ($ands) {
$query .= " WHERE " . implode(" AND ", $ands);
}
$conn = new PDO('mysql:host=127.0.0.1; dbname=test', 'root', '');
$stmt = $conn->prepare($query);
$stmt->execute($bind_array);
foreach ($stmt as $row) {
print_r($row);
}
}
更新:
如果您有两个参数price1[]
和price2[]
,则将price
循环更改为:
foreach($price1 as $i => $price) {
$ors[] = "price BETWEEN :pricelow{$i} AND :pricehigh{$i}";
$bind_array[":pricelow{$i}"] = $price;
$bind_array[":pricehigh{$i}"] = $price2[$i];
}
我恐怕您不能像试图做的那样迭代陈述。而是使用获取方法访问查询的结果:
while ($row = $stmt->fetch([fetch mode, e.g., PDO::FETCH_ASSOC])) {
print_r($row);
}
关于您遇到的"数组到字符串转换"错误,我怀疑一个或多个帖子变量实际上是一个数组。要检验此假设,请尝试print_r($ _ post)。