gpt4 book ai didi

php - MySQL where 子句中的一个或多个参数

转载 作者:行者123 更新时间:2023-11-29 01:26:30 25 4
gpt4 key购买 nike

我有一个用户可以输入的表单

Shape = Round, Triangle, Square, Rectangle, Rhombus, Kite, Decagon
Color = Red, Black, Green, Yellow, Blue, White
Size = 1, 2, 3 … 11

并且在数据库中,有多个项目具有上述特征例如,尺寸为 5 的红色圆形和尺寸为 1 的黑色圆形,依此类推。

用户可以只选择一个或全部 3 个特征并提交表单,我想显示已建立的结果。示例:如果用户仅选择颜色,则结果应显示所选颜色的所有项目,无论其形状或大小如何。如果用户选择形状和颜色,则所有已选择形状和颜色的项目。我的问题是如何创建查询来执行此操作?

我尝试的代码

if (!empty($_POST["shape"])):
$shape = trim($_POST["shape"]);
else:
$shape = "";
endif;

if (!empty($_POST["color"])):
$color = strtolower(trim($_POST["color"]));
else:
$color = "";
endif;
if (!empty($_POST["size"])):
$size = trim($_POST["size"]);
else:
$size = "";
endif;

SQL = SELECT * FROM items WHERE item_shape = $shape && item_color = $color && item_size = $size

结果始终为 0,除非我只使用一个 WHERE 子句,它的工作方式就像仅塑造并从命令中删除其他子句一样。

另外,我试着这样改

if (!empty($_POST["shape"])):
$shape = trim($_POST["shape"]);
else:
$shape = " Round, Triangle, Square, Rectangle, Rhombus, Kite, Decagon";
endif;

// changed all post parameters sane wat u did with shape

SQL = SELECT * FROM items WHERE item_shape in ($shape) && item_color in ($color) && item_size = ($size)

我怎样才能做到这一点?感谢您的宝贵时间。

最佳答案

你可以尝试这样的事情:

// add as many features as you like to filter in this array
$features = array();

if (!empty($_POST["shape"])):
$features['shape'] = trim($_POST["shape"]);
endif;

if (!empty($_POST["color"])):
$features['color'] = strtolower(trim($_POST["color"]));
endif;

if (!empty($_POST["size"])):
$features['size'] = trim($_POST["size"]);
endif;

$sql = "SELECT * FROM items";

// if there is any feature in the array
if ( ! is_null($features))
{
$i = 0;
$len = count($features);

// check each one of the features
foreach ($features as $feature => $feature_value) {
if ($i == 0)
{
// if the first item, use WHERE
$sql .= ' WHERE ';
} else
{
// else, use &&
$sql .= ' && ';
}

$sql .= 'item_' . $feature . ' = ' . $feature_item;
$i++;
}
}

关于php - MySQL where 子句中的一个或多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45288304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com