【问题标题】:Mysqli query using $_get where a value is missing [duplicate]使用 $_get 在缺少值的情况下进行 Mysqli 查询[重复]
【发布时间】:2016-10-11 22:15:49
【问题描述】:

我有一个下拉框,用户可以在其中选择一个位置。然后,有一个文本框,他们可以在其中输入最高租金(将有更多选项,但为了简单起见,示例中的这些选项)。然后这将转到 results.php 页面并使用 $_GET 数组提取值并查询数据库

如果两个字段都完整,这可以正常工作,但如果他们只想按位置搜索并将租金字段留空,则它不起作用并在 URL 中显示 results.php?loc=york&rent=,然后我用过AND函数没有结果?

我是 PHP 的新手,非常感谢任何能指出我正确方向或在 google 中搜索的正确术语的人?

<?php
$location = $_GET['loc'];
$rent=$_GET['rent'];

$result = $mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city &&'$rent'>rent_price  ORDER BY ID ASC");

?>

【问题讨论】:

  • 由于某种原因,它一直缺少我的问题的开头部分!,应该阅读,我有一个下降......
  • 你应该使用准备好的语句..
  • If ($rent) { Add condition to a query }

标签: php sql search filter


【解决方案1】:

试试这个

   <?php

      // you can check for sql injection
      $location = $_GET['loc'];
      $rent=$_GET['rent'];

      // check if $_GET['rent'] is provided and has a value
      if( isset( $_GET['rent'] ) && $_GET['rent'] ) {

        $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' AND rent_price < '$rent'  ORDER BY ID ASC" );

       // do remaining stuff

      } else { 

       // rent is not provided
       $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location'  ORDER BY ID ASC");

       // do other stuff

      }



    ?>

【讨论】:

    【解决方案2】:

    您可以创建 2 个查询,也可以只创建一个带有一些变量的查询。

    $rent = $_GET['rent'];
    $rent_options = "";
    if(isset($rent)) //add condition
     {
          $rent_options .= "&& \'rent\'>rent_price";
     }
    $mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city".$rent_options." ORDER BY ID ASC"); 
    

    这样,假设他们选择了租金选项,它将被添加到查询中。如果不是,它将只是空白并被忽略。

    【讨论】:

    • 我猜可能不会被忽略
    • 感谢您的所有帮助,但这似乎是我轻松添加更多选项的最佳选择,谢谢
    【解决方案3】:

    如果 $rent 是空的,你必须在查询数据库之前先检查它。

    if(!empty($rent))
    {
         $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' and rent_price<'$rent' ORDER BY ID ASC");
    } else {
         $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC");
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 2021-11-15
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多