duanlan5320 2016-10-07 15:57
浏览 119
已采纳

如果值为空,如何忽略SQL Select命令

I have this SQL query:

$sql2 = "SELECT * FROM MyTable WHERE time1='".$_POST['time']."' AND type1='".$_POST['type']."';

The result:

$result1 = $conn->query($sql2);

if ($result1->num_rows > 0) {
    // output data of each row
    while($row = $result1->fetch_assoc()) {

        echo $row["name1"];
  • name1 row is the name of the activity in database.

The HTML form has these two select lists:

<select id="time" name="time" required="" data-do-validate="true">
    <option value="">Select ...</option> // this is the NULL value
    <option value="time1">Type 1</option>
    <option value="time2">Type 2</option>
    <option value="time3">Type 3</option>
    <option value="time4">Type 4</option>
                        </select>

<select id="type" name="type" required="" data-do-validate="true">
    <option value="">Select ...</option> // this is the NULL value
    <option value="type1">Type 1</option>
    <option value="type1">Type 2</option>
    <option value="type1">Type 3</option>
    <option value="type1">Type 4</option>
                        </select>

So what I try to do is selecting from the database the name of all activities with matching data submitted by the HTML form.

BUT what I additionally want is to ignore the SQL Select for the Time ( For example ) if the user leave the value empty ( Select ... ), the result in this case will be the names of all activities based only on the Type. And if he select a time and a type the result in this case will be more specified based on the Time and the Type of the activity.

What can I do?

Thank you!

  • 写回答

3条回答 默认 最新

  • douzhang1955 2016-10-07 16:07
    关注

    You could build your Statement depending on the $_POST Values (by the way, in productive you should't use $_POST values directly in the SQL statement).

    $connect = "";
    $sql2 = "SELECT * FROM MyTable ";
    
    if($_POST['time']!='' || $_POST['type']!='') {
      $sql2 .= "WHERE ";
      if($_POST['time']!='') {
          $sql2 .= "time1='".$_POST['time']."'";
          $connect = " AND ";
      }
      if($_POST['type']!='') {
         $sql2 .= $connect . "type1='".$_POST['type']."'";
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测