doudanma9706 2017-04-23 16:50 采纳率: 100%
浏览 73
已采纳

sql pdo选择菜单值$ _POST

I made 2 populated selectmenu's to make queries to my sql database. The first option-tags of all select menu's have value="" Now everything works fine when I do select options of all 2 selectmenu's. But If I don't choose 1 or more options, the query doesn't work.

One of the select menu's:

<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();
  • 写回答

1条回答 默认 最新

  • du970294 2017-04-23 17:04
    关注

    You can add check for that :

    $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化