实时AJAX搜索同时具有多个输入PHP / MySQL

时间:2014-04-19 01:28:13

标签: javascript php jquery mysql ajax

我正在使用两个输入进行AJAX(粉末角的数据库)的实时搜索,第一个用于年度,第二个用于冲突。我遇到的问题是当其中一个输入为空时,它只返回表中没有列出日期或冲突名称的元素。相反,我希望空白输入表现为null,并显示表中的所有内容。我可以使用条件来修复日期部分以检查是否(!$ date),但如果用户再次选择空白,我无法使选择输入的行为方式相同。

有关如何解决此问题的任何想法?特别是在没有大量PHP的一个查询中if / else?

HTML

<h1> Powder Horn Search Engine </h1>




Date <input id="date" type="text" name="variable">

To <select id="conflict">
        <option>  </option>
        <option value="French & Indian War">French & Indian War</option>
        <option value="Revolutionary War">Revolutionary War</option>
        <option value="War of 1812">War of 1812</option>    
    </select>

<div id="result">
</div>

的Javascript

        var date="";
var conflict=""

    $(document).ready( function () {    
//Send date to PHP
$("#date").keyup(function(){
    date = $("#date").val();
    conflict=$("#conflict").val();

    $.ajax({
          type: "POST",
          data: {date: date, conflict:conflict},
          url: "powderhornsearch.php",
            success: function(data){ //response param
            $("#result").html(data);
            }

        });
});

//Send conflict to PHP
$("#conflict").change(function(){
conflict=$("#conflict").val();
date = $("#date").val();

$.ajax({
          type: "POST",
          data: {conflict: conflict, date:date},
          url: "powderhornsearch.php",
            success: function(data){ //response param
            $("#result").html(data);
            }

        });


}); 
    });

PHP

    $date = $_POST['date'];
$conflict=$_POST['conflict'];
    $result = mysql_query ("SELECT * FROM powderhorns WHERE Date LIKE $date AND Conflict LIKE '$conflict'  ", $connection);
    if (!$result) {
            die("Database query failed:" . mysql_error());
        }
    echo "<table>";
    while ($row = mysql_fetch_array($result)) {
    echo "<tr>";
        echo "<td>".$row[0]."</td>".
            "<td>".$row[1]."</td>".
            "<td>".$row[2]."</td>".
            "<td>".$row[3]."</td>".
            "<td>".$row[4]."</td>";     
    echo "</tr>";   
    }
    echo "</table>";

修改

我将空白选择的值更改为“1”,因为看起来MySQL的空字符串有问题。我使用以下代码完成了所有工作。由于我是编程新手,如果有人建议如何使它更加浓缩或优雅,我会喜欢你的想法。非常感谢!

    if (!$date) {
$date="";
}

if ($conflict=="1" && !$date)
{
$result = mysql_query ("SELECT * FROM powderhorns", $connection);
}

else if ($conflict==1){
    $result = mysql_query ("SELECT * FROM powderhorns WHERE Date LIKE $date  ", $connection);
}

else if (!$date && $conflict){
    $result = mysql_query ("SELECT * FROM powderhorns WHERE Conflict LIKE '$conflict'  ", $connection);
}

else{
    $result = mysql_query ("SELECT * FROM powderhorns WHERE Conflict LIKE '$conflict' and Date LIKE $date  ", $connection);
}   

1 个答案:

答案 0 :(得分:0)

将其更改为:

$condition=1;
if(trim($date)) $condition .=" and Date LIKE '$date'";
if(trim($conflict)) $condition .="  and Conflict LIKE '$conflict'";

$result = mysql_query ("SELECT * FROM powderhorns WHERE $condition ", $connection);