我试图显示产品的分页和排序使用 AJAX 和PHP的每一个类别,但我得到一个错误,如下所述

vuktfyat  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(105)

我在导航栏上的所有类别。我试图显示产品foreach类别,当我点击该类别。到目前为止,产品正在显示,但这些类别还没有产品,当点击我得到下面的错误
致命错误:未捕获的类型错误:usort():参数#1($array)必须是数组类型,null在C:\xampp\htdocs\securefiles\main\producta.php:75堆栈跟踪:#0 C:\xampp\htdocs\securefiles\main\producta.php(75):usort(NULL,'sortByQuery')#1 C:\xampp\htdocs\securefiles\main\categories.php(141):2019 - 05 - 22 01:01:00:00:00:00
我没有得到这个错误时,点击类别有产品。
分页并不适用于所有的页面。当我单击一个页面时,窗口只是滚动到顶部。
我的PHP代码如下

`$query = "SELECT   sellers.room,sellers.seller_id,sellers.image,price,sellers.category_id,sellers.type,sellers.badge,categories.category, 
 COUNT(DISTINCT comments.user_id) AS total, AVG(rating) AS rate,AVG(odds) AS odda FROM sellers 
INNER JOIN categories ON sellers.category_id=categories.id 
LEFT JOIN comments ON sellers.seller_id=comments.seller_id 
LEFT JOIN posts ON sellers.seller_id=posts.seller_id
LEFT JOIN keywords ON sellers.seller_id=keywords.seller_id
WHERE categories.id = '$_GET['category_id']'
GROUP BY sellers.seller_id ORDER BY rate DESC";
    $statement = $conn->prepare($query);
    $statement->execute();
    $statement->setFetchMode(PDO::FETCH_ASSOC); //PDO::FETCH_OBJ
    $result = $statement->fetchAll();
if($result) {
    foreach($result as $product) {
        $products[]=$product;
    }

}
    // Filter query
    $cat_filter = isset($_POST['category_id']) ? $_POST['category_id'] : '';
    $seller_filter = isset($_POST['level']) ? $_POST['level'] : '';
    $sub_filter = isset($_POST['type']) ? $_POST['type'] : '';
    $search_filter = isset($_POST['search']) ? $_POST['search'] : '';

    // Default limit
    $limit = isset($_POST['per-page']) ? $_POST['per-page'] : 3;

    // Default offset
    $offset = 0;
    $current_page = 1;
    if(isset($_POST['page-number'])) {
        $current_page = (int)$_POST['page-number'];
        $offset = ($current_page * $limit) - $limit;
    }

    // filter products array based on query
    if(!empty($seller_filter) || !empty($seller_filter) || !empty($sub_filter) || !empty($search_filter)) {
        $filtered_products = array();
        foreach($products as $product) {
            if(!empty($cat_filter) && !empty($seller_filter) && !empty($sub_filter) && !empty($search_filter)) {

                if((strpos($product['tag_name'], $search_filter) !== false || $product['room'] == $search_filter) && ($product['category_id'] == $cat_filter) && ($product['type'] == $sub_filter) && ($product['badge'] == $seller_filter)) {
                    $filtered_products[] = $product;
                }

            } elseif(!empty($cat_filter) && $product['category_id'] == $cat_filter && !empty($sub_filter) && $product['type'] == $sub_filter) {

                $filtered_products[] = $product;
            } elseif(!empty($cat_filter) && $product['category_id'] == $cat_filter && !empty($seller_filter) && $product['badge'] == $seller_filter) {

                $filtered_products[] = $product;
            } elseif(!empty($search_filter) && (strpos($product['tag_name'], $search_filter) !== false || $product['room'] == $search_filter) && !empty($cat_filter) && $product['category_id'] == $cat_filter) {

                $filtered_products[] = $product;
            }
        }

        $products = $filtered_products;
    }
// Sorting
function sortByQuery($a, $b) {

    $sort_by = isset($_POST['sort-by']) ? $_POST['sort-by'] : 'room';
    $sort_order = isset($_POST['sort-order']) ? $_POST['sort-order'] : 'ASC';

    if ($sort_order == 'DESC') {
        return $a[$sort_by] < $b[$sort_by];
    } else {
        return $a[$sort_by] > $b[$sort_by];
    }
}

usort($products, 'sortByQuery');

// Alter the array
$paged_products = array_slice($products, $offset, $limit);

// Define total products
$total_products = count($products);

// Get the total pages rounded up the nearest whole number
$total_pages = ceil( $total_products / $limit );

$paged = $total_products > count($paged_products) ? true : false;

if (count($paged_products)) {
    foreach ($paged_products as $product) { ?>
                    <div class="card col-sm-3 me-1 mt-3 product-wrapper"  style="width:12.7rem;height: 22rem;">
                        <?php echo '<a href=main/products.php?category='.preg_replace('#[-]+#','-',trim($product['category'])).'&room='.preg_replace('#[-]+#','-',trim($product ['room'])).'&seller_id='.preg_replace('#[-]+#','-',trim($product ['seller_id'])).'>
                        <img src="../seller/' .htmlspecialchars($product ['image']).'" class="img-top  img-fluid bg-light" alt="...">
                        </a>';?> 
                        <div class="card-body">
                            <div class="row border-bottom">
                                <h5 class="card-title text-center fw-bolder fs-5 mt-3"><?php echo htmlspecialchars($product ['room']);?></h5>
                                <p class="text-center text-decoration-none text-dark"  style="font-size:1rem;" ><?php echo htmlspecialchars($product ['category']);?></p>
                                <p class="text-danger"><i class="fa-solid fa-star"></i><?php echo htmlspecialchars($product ['rate']);?>
                                    <span class="text-end fw-light text-dark">(<?php echo htmlspecialchars($product ['total']);?>)</span>
                                </p>
                            </div><p class="card-title text-start fw-bolder text-decoration-none text-dark"                  style="font-size:0.7rem;">STARTING AT
                            <span class="text-start fw-bolder text-decoration-underline" style="font-size:.8rem;">US &dollar;<?php echo htmlspecialchars($product ['price']);?></span>
                            </p>
                        </div>
                    </div>
                
                    <?php }
                }

                else {
                    echo '<p class="alert alert-warning" >No results found.</p>';
                 } 
                if ($paged) {
                    require('pagination.php');
                }

我的页面脚本

<?php
    $current_query = isset($_POST) ? 'data-query="' . http_build_query($_POST) . '"' : '';
?>
<nav class="col-md-12 mt-3" >
  <ul class="pagination">
      
        <li class="page-item <?php echo $current_page === 1 ? 'disabled' : ''; ?>">
          <a class="page-link" href="#" data-page-number="<?php echo $current_page - 1; ?>" <?php echo $current_query; ?> >
            <span>«</span>
          </a>
        </li>
    
    <?php
    
    for($page_number = 1; $page_number <= $total_pages; $page_number ++) { ?>
             <li class="page-item <?php echo isset($_POST['page-number']) && $_POST['page-number'] == $page_number ? 'active' : ''; ?>"><a class="page-link" href="#" data-page-number="<?php echo $page_number; ?>" <?php echo $current_query; ?>><?php echo $page_number; ?></a></li>
    
    <?php } ?>
    
        <li class="page-item <?php echo $current_page === (int)$total_pages ? 'disabled' : ''; ?>">
          <a class="page-link" href="#" data-page-number="<?php echo $current_page + 1; ?>" <?php echo $current_query; ?>>
            <span>»</span>
          </a>
        </li>
  </ul>
</nav>

我的 AJAX 脚本用于在页面上回声数据

$(document).on('change', '#category_id', function(){
        var id = $(this).attr("category_id");

        $.ajax({
            url:"producta.php?category_id="+id, 
            method:"POST",    
            data:{'category_id':id},
            success:function(data){
                $('#all-products').html(data);
            }
        })
        $(document).on('click', '.page-link', function(){
            var page_number = $(this).data('page-number');
            var current_query;
            if( $(this).data('query') ) {
            current_query = '?' + $(this).data('query');
            }
            else {
                current_query = '';
            }
            $.ajax({
                    url:"producta.php?" + current_query , 
                    method:"POST",   
                    data:{'page-number' : page_number},
                    success:function(data){
                        $('#all-products').html(data);
                    }
             })
             $(document).on('submit', '#filter-form', function(){
                var form = $(this);
                $.ajax({
                    url:"producta.php?category_id="+id,  
                    method:"POST",   
                    data : $('#form').serialize() + "&category_id="+id ,
                    success:function(data){
                        $('#all-products').html(data);
                    }
             })
             });
        });
    });
whitzsjs

whitzsjs1#

如果你的查询没有找到任何记录,则if所包围的代码:

if($result) {
    
    foreach($result as $product) {
        $products[]=$product;
    }

}

没有执行,所以 $products 不存在,它的计算结果为NULL。为了快速解决这个问题,将$products初始化为空数组:

$products = [];

if($result) {
   //...

但是,我必须警告您,您的代码优化得很差,您将面临SQL注入。
我看到您使用了一个预处理语句,但随后使用字符串连接来组成查询,而不是使用参数,这是一个糟糕的方法,它会使您暴露于SQL注入
在我看来,将查询结果逐行复制到一个新数组也是毫无意义的:

foreach($result as $product) {
     $products[]=$product;
}

你可以直接使用fetch结果($result
此外,分页、排序和数据过滤必须直接在查询中执行,从DB中读取所有行然后在代码中过滤它们并不方便:想象一下你要在成千上万的台词上表演

相关问题