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 Acrn IVSHMEM doorbell问题
  • ¥15 yolov5中的val测试集训练时数量变小问题
  • ¥15 MPLS/VPN实验中MPLS的配置问题
  • ¥15 materialstudio氢键计算问题
  • ¥15 echarts图表制作
  • ¥15 halcon根据玻璃面板纹路取区域
  • ¥15 HFSS设计小型化180度耦合器
  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理