【问题标题】:Filtering data with a PHP, Jquery, AJAX form mechanism and data from Database使用 PHP、Jquery、AJAX 表单机制和数据库中的数据过滤数据
【发布时间】:2026-02-02 00:00:01
【问题描述】:

我正在尝试创建一个利用 PHP 和 Jquery AJAX 表单提交机制的表单,该机制“过滤”来自 mySQL 数据库的数据。

表单中有三个带有“提交”按钮的下拉栏,它将“过滤”数据库中的数据。但是,用户不需要从下拉列表中的所有选项中进行过滤 - 'cuisine'、'pricing'、'location'。我需要创建某种查询,如果未使用下拉列表,则不会在过滤器中使用它。

下面是我开始的内容。我目前只使“美食”过滤器起作用。

if (isset($_GET['cuisine']) && isset($_GET['pricing'])) {
    $cuisine = $_GET['cuisine'];
    $pricing = $_GET['pricing'];
    $location = $_GET['location'];

        if ($cuisine != 'Cuisine') { 
            $cuisineUse = true; 
        } else { $cusineUse = false; }

        if ($pricing != 'Price Range') { 
            $pricingUse = true; 
        } else { $pricingUse = false; } 

        if ($location != 'Location') { 
            $locationUse = true; 
        } else { $locationUse = false; }


// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM restaurants 
WHERE Cuisine='$cuisine'
ORDER BY restaurantID
") 
or die(mysql_error()); 

还有 Jquery:

<script>
  /* attach a submit handler to the form */
  $("#searchForm").submit(function(event) {

    /* stop form from submitting normally */
    event.preventDefault(); 

    /* get some values from elements on the page: */
    var $form = $( this ),
        term = $form.find( 'input[name="cuisine"]' ).val(),
        url = $form.attr( 'action' );

    /* Send the data using post and put the results in a div */
    $.post( url, { s: term },
      function( data ) {
          var content = $( data ).find( '#content' );
          $( "#jsDiv" ).empty().append( content );
      }
    );
  });
</script>

P.S 用户也可以同时使用两个或多个“过滤器”。

【问题讨论】:

    标签: php jquery mysql ajax forms


    【解决方案1】:

    您正在发送一个 POST 请求,因此您应该使用 $_POST 而不是 $_GET。此外,发送时美食名称的值是 s 而不是 cuisine 所以它应该是:

    if($_POST['s'] != '') {
       ...
       $result = mysql_query("SELECT * FROM restaurants WHERE Cuisine='$cuisine' ORDER BY restaurantID");
    } else {
       $result = mysql_query("SELECT * FROM restaurants ORDER BY restaurantID");
    }
    

    如果没有设置美食,你只需要删除 where 子句。

    【讨论】:

    • 嗯.. 如果其中有多个在场,这将如何运作。例如,如果用户想按美食和价格过滤它们?还是位置和价格?等等……
    【解决方案2】:

    试试:

    //USE mysql_real_escape_string for your variables //is it POST or GET $qry = "SELECT * FROM restaurants WHERE cuisine = '".$cuisine."'"; $qry .= empty($_POST['pricing']) ? " " : " AND pricing = '".$_POST['pricing']."'"; $qry .= empty($_POST['location']) ? " " : " AND location = '".$_POST['location']."'"; $qry .=" ORDER BY restaurantID";

    【讨论】:

    • 我不太明白这个是怎么回事。请您再解释一下好吗?