简体   繁体   English

PHP和MySql中的多个搜索条件

[英]Multiple Search Criteria in PHP and MySql

I'm working on a motor dealership website. 我正在汽车经销商网站上。 This dealership uses a third-party desktop application to manage the stock and the vehicles on sale. 该经销商使用第三方桌面应用程序来管理库存和待售车辆。 This third-party application saves the vehicle data to an Access Database (.mdb). 该第三方应用程序将车辆数据保存到Access数据库(.mdb)。 I successfully connect to this database, as well as view individual records and so forth. 我成功连接到该数据库,并查看了各个记录等。 All is great up to this point. 到目前为止,一切都很好。

The final piece of the puzzle is an advanced search criteria. 难题的最后一部分是高级搜索条件。 This search criteria has six inputs; 此搜索条件有六个输入; brand, model (the brand and model inputs are text and they are also cascading dropdowns using AJAX), branch, year (text), min price and max price (the two price inputs are of number data type in the database). 品牌,型号(品牌和型号输入是文本,并且它们也使用AJAX进行级联下拉),分支,年份(文本),最低价格和最高价格(两个价格输入是数据库中数字数据类型)。

Users will very likely not use all of the available inputs because more often than not, that would give them no results. 用户很可能不会使用所有可用的输入,因为通常情况下,它们不会产生任何结果。

Also, if the search works after all that, and someone searches something but that something is not available in the database, a message has to appear informing the user that the requested vehicle is currently not available. 同样,如果搜索在这之后仍然有效,并且有人在搜索某项但数据库中某项不可用,则必须出现一条消息,通知用户所请求的车辆当前不可用。 How would I go about doing something like that? 我将如何去做这样的事情?

Here's my code so far. 到目前为止,这是我的代码。

<?php

      $dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";

      // Throws an error if the database cannot be found
      if (!file_exists($dbName)) {
        die("Could not find database file.");
      }

      // Connects to the database
      // Assumes there is no username or password
      $conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');

      if (isset($_REQUEST['submit'])) {
        $searchMake = addslashes($_POST['makeSelection']);
        $searchModel = addslashes($_POST['modelSelection']);
        $searchBranch = addslashes($_POST['branchSelection']);
        $searchYear = addslashes($_POST['yearSelection']);
        $minPrice = addslashes($_POST['minPriceSelection']);
        $maxPrice = addslashes($_POST['maxPriceSelection']);

        $sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle WHERE Price BETWEEN $minPrice AND $maxPrice AND Make LIKE '$searchMake' AND Model LIKE '$searchModel' AND Year LIKE '$searchYear' AND Branch LIKE '$searchBranch'";
        $rs = odbc_exec($conn, $sql);


      //} else {
        //$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle ORDER BY Make";
        //$rs = odbc_exec($conn, $sql) or die (odbc_errormsg());

      }   



          echo "\t" . "<tr>\n";

              echo "\t" . "<th>Make</th><th>Model</th><th>Year</th><th>Price</th><th>Special Price</th><th>Location</th><th>Stock Number</th>" . "\n";

                  while (odbc_fetch_row($rs)) { 
                      $id = odbc_result($rs, Id);
                      $make = odbc_result($rs, Make);
                      $model = odbc_result($rs, Model);
                      $year = odbc_result($rs, Year);
                      $price = odbc_result($rs, Price);
                      $specialPrice = odbc_result($rs, SpecialPrice);
                      $branch = odbc_result($rs, Branch);
                      $stockNo = odbc_result($rs, StockNO);

                          echo "\t" . "<tr>\n";
                              echo "\t\t" . "<td>" . $make . "</td><td><a href=/newsite/selected-vehicles?Id=$id>" . $model . "</a></td><td>" . $year . "</td><td>" . $price . "</td><td>" . $specialPrice . "</td><td>" . $branch . "</td><td>" . $stockNo . "</td>\n";

                          echo "\t" . "</tr>\n";
                  }

      odbc_free_result($rs);
      odbc_close($conn);

      // This message is displayed if the query has an error in it
      if (!$rs) {
          exit("There is an error in the SQL!");
      }

  ?>

How would I make the message appear? 我如何使消息出现?

EDIT: The query works now and it displays the derisred results based on selections made, but all the selections have to be made otherwise it doesn't display anything. 编辑:该查询现在工作,并根据选择显示已拒绝的结果,但是必须进行所有选择,否则将不显示任何内容。

Please keep in mind that the brand MUST be selected. 请记住,必须选择品牌。 It can't be all brands. 不可能是所有品牌。 Otherwise you can just view the whole table. 否则,您只能查看整个表格。

How can I structure the above query to have an "all models" and "any branch" and "any year" and "any price" as valid selections? 如何构造上述查询,以将“所有模型”,“任何分支机构”,“任何年份”和“任何价格”作为有效选择?

You need to think through all the possible combination of inputs and how that's going to affect the query that gets sent to the database. 您需要考虑所有可能的输入组合,以及这将如何影响发送到数据库的查询。 For example, your query is constructed via: 例如,您的查询是通过以下方式构造的:

SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO
FROM Vehicle
WHERE 
    Price >= $minPrice AND
    Price <= $maxPrice AND
    Make LIKE 'searchMake' AND
    Model LIKE 'searchModel' AND
    Branch LIKE '$searchBranch'
    AND Year LIKE '$searchYear'

(I've broken up the query to make it a little easier to read). (我对查询进行了细分,使其更易于阅读)。

Now ask yourself: "what happens if $minPrice is empty"? 现在问问自己:“如果$minPrice为空,会发生什么?” The resulting query is going to look like this: 结果查询将如下所示:

SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO
FROM Vehicle
WHERE 
    Price >=  AND
    Price <= 100 AND
    Make LIKE 'something' AND
    Model LIKE 'something' AND
    Branch LIKE 'something'
    AND Year LIKE 'something'

That's not valid SQL: you're gonna get an error. 那是无效的SQL:您会得到一个错误。 Similar things can & will happen with all the other values you're inserting in this way. 以这种方式插入的所有其他值可能也会发生类似的情况。

Also, I notice from your error message that you're searching for values like --All Models-- . 另外,我从您的错误消息中注意到,您正在搜索--All Models--类的值。 Chances are, there are no models in the inventory with that name. 很有可能,库存中没有使用该名称的模型。 If you want to handle values like that, you'll need to adjust them in the code before submitting them to the database. 如果要处理类似的值,则需要先在代码中对其进行调整,然后再将其提交给数据库。

There are a couple of ways you could handle building your queries: 您可以通过以下两种方法来构建查询:

  1. you can write your code in such a way that it rebuilds the list of WHERE clauses based on the values provided by the user, or 您可以以这样的方式编写代码,使其基于用户提供的值来重建WHERE子句的列表,或者
  2. you can provide sensible defaults for any values that the user omits and replace any values like "All Models" with something that will match all values in the database. 您可以为用户忽略的任何值提供合理的默认值,并使用与数据库中所有值匹配的值替换“ All Models”之类的任何值。

Now, on the question of how to get the results you expect: think about how you want to search. 现在,关于如何获得期望的结果的问题:考虑如何搜索。 The way you've got it, you will only get results if all the conditions match - ie. 实现方式,只有在所有条件都匹配的情况下,您才能获得结果-即。 if the user enters Make="Ford" and Model="Civic" - you're gonna get nothing. 如果用户输入Make =“ Ford”和Model =“ Civic”-您将一无所获。 This might be the way you want it to work, or you might want it to return a list of all the Fords and all the Honda Civics. 这可能是您希望它工作的方式,或者您可能希望它返回所有福特和所有本田思域的列表。

Finally, on the subject of @Dagon's comment above - you should look into using parameters for your queries. 最后,关于上面@Dagon的注释,您应该研究使用参数进行查询。 That will remove the need to use functions like addslashes and will also protect you from SQL injection. 这将消除对使用诸如addslashes功能的需求,还将保护您免受SQL注入的侵害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM