我有一个多领域的php搜索表。将通配符添加到其中一个搜索字段时,会导致其他字段检索数据库中的所有数据。如果没有通配符,country只查找国家,cityname只查找城市:
$sql = " SELECT * FROM `epic_schools_tbl` WHERE ";
if (!empty($_POST['submit'])) {
if (isset($_POST['country'])) {
$country = $_POST['country'];
$sql .= " `country` = :country ";
}
if (isset($_POST['cityname'])) {
$cityname = $_POST['cityname'];
$sql .= " OR `city` = :cityname ";
}
$stmt = $pdo->prepare($sql);
$stmt->execute(array($country,$cityname));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<p>" . $row['country'] . "</p><p>" . $row['city'] . "</p>" . PHP_EOL;
}
}
添加通配符(学名)时:
$sql = " SELECT * FROM `epic_schools_tbl` WHERE ";
if (!empty($_POST['submit'])) {
if (isset($_POST['country'])) {
$country = $_POST['country'];
$sql .= " `country` = :country ";
}
if (isset($_POST['schoolname'])) {
$schoolname = $_POST['schoolname'];
$sql .= " OR `school_name` LIKE :schoolname ";
}
if (isset($_POST['cityname'])) {
$cityname = $_POST['cityname'];
$sql .= " OR `city` = :cityname ";
}
$stmt = $pdo->prepare($sql);
$stmt->execute(array($country,"%$schoolname%",$cityname));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<p>" . $row['country'] . "</p><p>" . $row['school_name'] . "</p><p>" . $row['city'] . "</p>" . PHP_EOL;
}
}
它使country和/或cityname检索数据库中的所有数据。select语句是否可以编写为接受一个带有通配符的输入,而其他输入的格式不是通配符?
1条答案
按热度按时间ltskdhd11#
部分解决方案包括在select语句中放置if函数。此外,如果保留为空,则替换或使用并有助于消除city字段或schoolname字段返回整个数据库。