【问题标题】:Multiple Select Filter - AJAX [closed]多选过滤器 - AJAX [关闭]
【发布时间】:2020-02-27 13:09:21
【问题描述】:

我想创建一个表单,用户可以在其中搜索某个人在特定月份的记录。 这是我的表格:

<div class="form-row">
   <div class="col-sm-4">
       <select class="form-control" name="name" id="name">  
          <option selected="selected" style="display:none" value="">Select Employee</option>
          <?php echo fill_employees($connect); ?>  <!---option list--->
       </select> 
   </div>
   <div class="col-sm-2">
       <select class="form-control" name="month" id="month">  
           <option selected="selected" style="display:none" value="0">Month</option>
           <option value="1">January</option>
           <option value="2">February</option>
           <option value="3">March</option>
           <option value="4">April</option>
           <option value="5">May</option>
           <option value="6">June</option>
           <option value="7">July</option>
           <option value="8">August</option>
           <option value="9">September</option>
           <option value="10">October</option>
           <option value="11">November</option>
           <option value="12">December</option>
         </select> 
    </div>
    <div class="col-sm-2">
        <select class="form-control" name="year" id="year">  
           <option selected="selected" style="display:none" value="">Year</option>
           <?php echo fill_year($connect); ?>  <!---option list--->
        </select> 
    </div>
 </div>
 <div class="row" id="show_data">Search Results</div>

下面是我的脚本:

 <script>  
    $(document).ready(function(){  
        $('#name'),$('#month'),$('#year').change(function(){  
            var name = $(this).val();
            var month = $(this).val()  ;
            var year = $(this).val();
            $.ajax({  
                    url:"search.php",
                    method:"POST",  
                    data:{name:name,month:month,year:year},
                    success:function(data){
                        $('#show_data').html(data);
                    }  
            });  
        });  
    });  
    </script>

这是我的 search.php 文件

<?php
$connect = mysqli_connect("localhost", "root", "", "test");

$output = '';
echo '<div class="fixed-header col-sm-12">';
echo '<table class="table table-hover table-sm">';
    echo '<thead class="thead-dark">';
        echo '<th style="width:15%; text-align:center;">Day</th>';
        echo '<th style="width:25%; text-align:center;">Date</th>';
        echo '<th style="width:20%; text-align:center;">Time In</th>';
        echo '<th style="width:20%; text-align:center;">Time Out</th>';
        echo '<th style="width:20%; text-align:center;">Total Hours</th>';
    echo '</thead>';

$qname = "SELECT * FROM employees";
    $valid_nm = array($qname);
    $valid_mo = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12');
$qyear = "SELECT year(timeIn) FROM attendance GROUP BY year";
    $valid_yr = array($qyear);

    $q = "SELECT name, timeIn, timeOut,
            date(timeIn) as date,
            month(timeIn) as month,
            year(timeIn) as year,
            TIMESTAMPDIFF(MINUTE, timeIn, timeOut)/60 AS total_hrs
        FROM attendance";

// initialize array for WHERE clause conditions
$where = array('TRUE');

if (in_array($_POST['name'], $valid_nm))
{
    $where[] = 'name = "' . $_POST['name'] . '"';
}
if (in_array($_POST['month'], $valid_mo))
{
    $where[] = 'month(timeIn) = "' . $_POST['month'] . '"';
}
if (in_array($_POST['year'], $valid_yr))
{
    $where[] = 'year(timeIn) = "' . $_POST['year'] . '"';
}

    $output = '';
    $sql = 'SELECT name, timeIn, timeOut,
            date(timeIn) as date,
            month(timeIn) as month,
            year(timeIn) as year,
            TIMESTAMPDIFF(MINUTE, timeIn, timeOut)/60 AS total_hrs
        FROM attendance
            WHERE  ' . implode(' AND ', $where);
    $result = mysqli_query($connect, $sql);
    while ($row = mysqli_fetch_array($result))
    {
        $output .= '<tr>';
            $output .= '<td style="width:15%; text-align:center;">'. date('l', strtotime($row["timeIn"])) .'</td>';
            $output .= '<td style="width:25%; text-align:center;">'. date('d-M-Y', strtotime($row["timeIn"])) .'</td>';
            $output .= '<td style="width:20%; text-align:center;">'. date('h:i A', strtotime($row["timeIn"])) .'</td>';
            $int = strtotime($row["timeOut"]);
                if ($int < 0)
                {
                    $output .= '<td style="width:20%; text-align:center">NA</td>';
                    $output .= '<td style="width:20%; text-align:center; color:red">NA</td>';
                } else {
                    $output .= '<td style="width:20%; text-align:center;">'. date('h:i A', strtotime($row["timeOut"])) .'</td>';
                    $output .= '<td style="width:20%; text-align:center;">'. number_format($row['total_hrs'],2) .'</td>';
                };
        $output .= '</tr>';
    }

    echo $output;
    echo '</table>';
    echo '</div>';
    ?>

据说它需要显示某个人的结果并选择月份和年份,但相反,它显示了我表上的所有数据。我认为错误在我的标准上,但我不知道具体在哪里。这是我第一次尝试 AJAX。

【问题讨论】:

标签: php mysql ajax filter


【解决方案1】:

坚持你的直接问题:

$qname = "SELECT * FROM employees";
$valid_nm = array($qname);
if (in_array($_POST['name'], $valid_nm))

您是否有任何名为“SELECT * FROM employees”的员工?因为这就是您要检查的内容。


如果您想更彻底地修复此代码,我建议您在 Javascript 中使用类似的方法,您可以在 serializing 表单中发送相关值,而不是出于某种原因将它们全部设置为相同的值:

$(document).ready(function(){  
    $('#name, #month, #year').change(function() {
        var form = this.closest("form");
        $.post("search.php", form.serialize(), function(data) {
            $('#show_data').html(data);
        });  
    });  
});

然后在您的 PHP 中,首先使用 PDO,它不那么冗长,并提供更现代的语法。使用prepared statements 确保安全,不要浪费资源检查“有效”数据。使用 alternative syntaxshort echo tags 将 PHP 拆分为 HTML 的较长部分,以保持整洁。并且始终为 HTML 输出 escape

<?php
$db = new \PDO("mysql:host=localhost;dbname=test", "root", "");
$sql = 'SELECT name, timeIn, timeOut, MONTH(timeIn) AS month, YEAR(timeIn) AS year,
        TIMESTAMPDIFF(MINUTE, timeIn, timeOut)/60 AS total_hrs
    FROM attendance
    WHERE ';
$where = ["TRUE"];
$params = [];
if (isset($_POST["name"])) {
    $where[] = "name = ?";
    $params[] = $_POST["name"];
}
if (isset($_POST["month"])) {
    $where[] = "month = ?";
    $params[] = $_POST["month"];
}
if (isset($_POST["year"])) {
    $where[] = "year = ?";
    $params[] = $_POST["year"];
}
$sql .= implode(" AND ", $where);
$stmt = $db->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);

/*
honestly, you should just be returning json_encode($data) here
the presentation of the data as a table doesn't belong here
*/

if (count($data) === 0) {
    echo '<p class="alert">No results found</p>';
    exit;
}

?>

<div class="fixed-header col-sm-12">
    <table class="table table-hover table-sm">
        <thead class="thead-dark">
            <th style="width:15%; text-align:center;">Day</th>
            <th style="width:25%; text-align:center;">Date</th>
            <th style="width:20%; text-align:center;">Time In</th>
            <th style="width:20%; text-align:center;">Time Out</th>
            <th style="width:20%; text-align:center;">Total Hours</th>
        </thead>
        <tbody>
<?php foreach($data as $row): ?>
            <tr>
                <td style="width:15%; text-align:center;"><?= htmlspecialchars(date('l', strtotime($row["timeIn"]))) ?></td>
                <td style="width:25%; text-align:center;"><?= htmlspecialchars(date('d-M-Y', strtotime($row["timeIn"]))) ?></td>
                <td style="width:20%; text-align:center;"><?= htmlspecialchars(date('h:i A', strtotime($row["timeIn"]))) ?></td>
    <?php if($row["timeOut"] < 0): ?>
                <td style="width:20%; text-align:center">NA</td>
                <td style="width:20%; text-align:center; color:red">NA</td>
    <?php else: ?>
                <td style="width:20%; text-align:center;"><?= htmlspecialchars(date('h:i A', strtotime($row["timeOut"]))) ?></td>
                <td style="width:20%; text-align:center;"><?= htmlspecialchars(number_format($row['total_hrs'],2)) ?></td>
    <?php endif; ?>
            </tr>
<?php endforeach; ?>
        </tbody>
    </table>
</div>

【讨论】:

  • 试图运行你的代码,现在它没有显示任何结果,我也将$qname = "SELECT * FROM employees";更改为$qname = "SELECT name FROM employees";,但我仍然没有得到我需要的结果
  • 好吧,您可能需要进行一些调试,我只是在脑海中输入了这个。如果不运行查询,将查询更改为什么也没关系。
【解决方案2】:

发生这种情况是因为 jquery 代码正在错误地查找输入。

具体来说,所有值都使用$(this).val();,这仅适用于实际刚刚更改的值,而不适用于其他 2。

另外,$('#name'),$('#month'),$('#year').change( 不是将处理程序附加到多个元素的有效语法。

试试这个:

$(document).ready(function(){  
    $('#name, #month, #year').change(function(){  
        var name = $('#name').val();
        var month = $('#month').val()  ;
        var year = $('#year').val();
        $.ajax({  
                url:"search.php",
                method:"POST",  
                data:{name:name,month:month,year:year},
                success:function(data){
                    $('#show_data').html(data);
                }  
        });  
    });  
});

附带说明,每次更改任何框时都执行 ajax 请求可能会损害您的用户体验。当用户从多个框中快速选择时,它会发送多个 ajax 请求(每个更改的元素一个),您不能指望这些响应总是以相同的顺序返回。做出所有选择后点击按钮可能会更好。

【讨论】:

  • @Richelle 很高兴它有帮助,请参阅我在底部添加的注释作为提醒:)
  • 对不起,我一定很头晕;)我尝试再次运行代码,它仍然显示我表上的所有数据,是的,你是对的,我真的需要放一个搜索按钮旁边
  • @Richelle 如果你在search.php 中执行var_dump($_POST),你会得到什么?
【解决方案3】:

所以我意识到我得到所有数据的原因。我没有正确获取nameyear 的数组。这是我下面的更新代码:

$query_nm = "SELECT name FROM employees";
$result_nm = mysqli_query($connect,$query_nm);
$valid_nm = array();
    while($row = mysqli_fetch_assoc($result_nm)) { 
        $valid_nm[] = $row['name']; 
        }

$valid_mo = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12');

$query_yr = "SELECT year(timeIn) FROM attendance GROUP BY year";
$result_yr = mysqli_query($connect,$query_yr);
$valid_yr = array();
    while($row = mysqli_fetch_assoc($result_yr)) { 
        $valid_yr[] = $row['year']; 
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多