我制作了2个填充的selectmenu来对我的sql数据库进行查询。所有选择菜单的第一个选项 - 标签都有值=“”现在,当我选择所有2个选择菜单的选项时,一切正常。但是如果我不选择1个或更多选项,则查询不起作用。
其中一个选择菜单:
<select name="titel" id="titel" value="">
<option value="">Selecteer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['titel'].'">'.$row['titel'].'</option>';
}
}else{
echo '<option value="">Language not available</option>';
}
?>
</select>
2nd page (search.php):
<?php
//load database connection
$host = "localhost";
$user = "...";
$password = "...";
$database_name = "...";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$titel=$_POST['titel'];
$version=$_POST['version'];
$query = $pdo->prepare("SELECT DISTINCT * FROM Library where titel = ? AND version = ?");
$query->bindValue(1, $titel, PDO::PARAM_STR);
$query->bindValue(2, $version, PDO::PARAM_STR);
$query->execute();
答案 0 :(得分:1)
您可以添加检查:
$sql = "SELECT DISTINCT * FROM Library";
if( (isset($_POST['titel']) && $_POST['titel'] != '') ) {
$sql .= " where titel =:titel";
if ( (isset($_POST['version']) && $_POST['version'] != '') ) {
$sql .= " AND version =:version";
}
}
if ( (isset($_POST['version']) && $_POST['version'] != '') && ! (isset($_POST['titel']) && $_POST['titel'] != '') ) {
$sql .= " where version =:version";
}
$query = $pdo->prepare($sql);
if( (isset($_POST['titel']) && $_POST['titel'] != '') ) {
$query->bindParam(':titel', $_POST['titel']);
}
if( (isset($_POST['version']) && $_POST['version'] != '') ) {
$query->bindParam(':version', $_POST['version']);
}
$query->execute();