MySQL中的动态生成多条件查询语句是指根据不同的条件组合生成相应的SQL查询语句。这种查询方式通常用于处理用户输入的不确定条件,使得查询更加灵活。
<?php
$conditions = [];
$params = [];
if (isset($_GET['brand'])) {
$conditions[] = "brand = '" . addslashes($_GET['brand']) . "'";
$params['brand'] = $_GET['brand'];
}
if (isset($_GET['price_min'])) {
$conditions[] = "price >= " . intval($_GET['price_min']);
$params['price_min'] = $_GET['price_min'];
}
if (isset($_GET['price_max'])) {
$conditions[] = "price <= "":wq' . intval($_GET['price_max']);
$params['price_max'] = $_GET['price_max'];
}
$sql = "SELECT * FROM products WHERE " . implode(' AND ', $conditions);
// 执行查询
$result = mysqli_query($conn, $sql);
?><?php
$sql = "SELECT * FROM products WHERE 1=1";
$params = [];
if (isset($_GET['brand'])) {
$sql .= " AND brand = ?";
$params[] = $_GET['brand'];
}
if (isset($_GET['price_min'])) {
$sql .= " AND price >= ?";
$params[] = intval($_GET['price_min']);
}
if (isset($_GET['price_max'])) {
$sql .= " AND price <= ?";
$params[] = intval($_GET['price_max']);
}
// 预处理语句
$stmt = $conn->prepare($sql);
// 绑定参数
foreach ($params as $key => $value) {
$stmt->bind_param($key + 1, $value);
}
// 执行查询
$stmt->execute();
$result = $stmt->get_result();
?>原因:直接将用户输入拼接到SQL语句中,容易受到SQL注入攻击。
解决方法:使用参数化查询,避免直接拼接用户输入。
原因:生成的SQL语句过于复杂,导致查询效率低下。
解决方法:
通过以上方法,可以有效解决MySQL中动态生成多条件查询语句的相关问题。