javascript - 使用 php 或 javascript 过滤结果

标签 javascript php mysql smarty

我是 PHP 开发新手,Smarty 使用 MySQL。我想就以下问题发表专家意见,或者任何好的建议都可以。

所以我做了一个 index.php 连接到数据库(MySQL)也是 Smarty,通过查询读取我的数据并从我的 index.tpl 文件中显示它们。对于我的产品,product.php 连接到数据库,进行查询,然后在 product.tpl 页面上显示我的产品。

对于我的 index.php,我想添加一个过滤器,按价格从高到低或从低到高显示产品。

你有什么建议:

您是建议我使用 Javascript 作为过滤器,还是只从数据库中查询选择值何时被选中?

或者怎么做才是最有效的方式?关于这方面的任何提示都会提前致谢。

我的数据库目前只有大约 3 个产品,我只是在测试。

.php

<?php

$new = ['product_id','product_category','product_price','product_quantity','product_about','product_color'];

//Database connection
$db = mysqli_connect('xxx','xxx','xxx','xxx') or die('Error connecting to MySQL server.');

//access Smarty template engine
require_once('Smarty-3.1.30/libs/Smarty.class.php');

$smarty = new Smarty();
$smarty->template_dir = 'views';
$smarty->compile_dir = 'tmp';


//query product page
$query = "SELECT * FROM cs_shop";

if ($productPrice > 0) {
    $query .= " WHERE `product_price` = ".$productPrice;
}


mysqli_query($db, $query) or die('Error querying database.');

$result = mysqli_query($db, $query);

if ( !empty($_GET['sort']) && $_GET['sort'] == 'PriceAsc' ) {
    $result =" ORDER BY `product_price` ASC";
} 
if ( !empty($_GET['sort']) && $_GET['sort'] == 'PriceDesc' ) {
    $result =" ORDER BY `product_price` DESC";
}




//query an array of products
$rows = array();

 //loop start
 while ($row = mysqli_fetch_array($result)) {
    $rows[] = array(
        'product_id' => $row['product_id'],
        'product_category' => $row['product_category'],
        'product_price' => $row['product_price'],
        'product_quantity' => $row['product_quantity'],
        'product_about' => $row['product_about'],
        'product_color' => $row['product_color']
    );
}

//db collect data
$smarty->assign('row', $rows); 
//template
$smarty->display('index.tpl');

mysqli_close($db);

?>

.tpl(这是显示产品列表的循环)

    <form method="get" name="sort">
    <select name="sort" id="sort">
                <option value=''>--Select--</option>
                <option value='PriceAsc'>high to low</option>
                <option value='PriceDesc'>low to high</option>
    </select>
    <input type="submit" value="Sort"/>
    </form>



<div class="test divider">
            {section name=prod loop=$row}
                <div class="colm3">
                    <div class="col3 r1">
                        <div class="products-container">
                            <h5>{$row[prod].product_name}</h5>
                            <a class="producy_img_link" href="#" >
                                <img src="{$row[prod].prod_img}" style="width:auto; height:255px;">
                            </a>
                        </div>
                    </div>

                    <a href="#">
                        <div class="block-right">
                            <h6>{$row[prod].product_vintage}</h6>
                            <h5>{$row[prod].product_veriatel}</h5>
                            <div>
                                <span class="price">R {$row[prod].product_price}</span>
                            </div>
                        </div>
                    </a>
                </div>
                {/section}
</div>

现在,每当我点击从高到低时,我希望产品按价格从高到低过滤,我认为使用查询会是一种简单的方法,但我坚持这样做。

最佳答案

您可以使用 AJAX要对表格进行排序,请提供表格标题 name属性并单击表头获取表头的名称属性并生成 AJAX调用你的PHP .

$('th').on('click', function () {
    var name = $(this).attr('name');

    console.log('AJAX will sort by: ' + name);
    // this is the AJAX call
    // $.post('somephpgage.php', {sortby: name}, function (response) {
    // $('#table-result').html(response);
    // });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table-result">
    <table style="width:100%">
        <thead>
        <tr>
            <th name="firstname">Firstname</th>
            <th name="lastname">Lastname</th>
            <th name="age">Age</th>
        </tr>
        </thead>
        <tr>
            <td>Jill</td>
            <td>Smith</td>
            <td>50</td>
        </tr>
        <tr>
            <td>Eve</td>
            <td>Jackson</td>
            <td>94</td>
        </tr>
    </table>
</div>

然后在你的PHP

<?php

    $new = ['product_id', 'product_category', 'product_price', 'product_quantity', 'product_about', 'product_color'];

    //Database connection
    $db = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx')
    or die('Error connecting to MySQL server.');

    //access Smarty template engine
    require_once('Smarty-3.1.30/libs/Smarty.class.php');

    $smarty = new Smarty();
    $smarty->template_dir = 'views';
    $smarty->compile_dir = 'tmp';
    //query product page
    $query = "SELECT * FROM cs_shop";


    if (!empty($_GET['sort']) && $_GET['sort'] == 'PriceAsc') {
        $query = "SELECT * FROM cs_shop ORDER BY price ASC";
    } elseif (!empty($_GET['sort']) && $_GET['sort'] == 'PriceDesc') {
        $query = "SELECT * FROM cs_shop ORDER BY price DESC";
    }

    $result = mysqli_query($db, $query);

    //query an array of products
    $rows = array();

    //loop start
    while ($row = mysqli_fetch_array($result)) {
        $rows[] = array(
            'product_id' => $row['product_id'],
            'product_category' => $row['product_category'],
            'product_price' => $row['product_price'],
            'product_quantity' => $row['product_quantity'],
            'product_about' => $row['product_about'],
            'product_color' => $row['product_color']
        );
    }

    //db collect data
    $smarty->assign('row', $rows);
    //template
    $smarty->display('index.tpl');

    mysqli_close($db);

    ?>

使用 AJAX 添加 id="sort-ajax"到这个 div <div class="test divider">

<select name="sort" id="sort">
    <option value=''>--Select--</option>
    <option value='PriceAsc'>high to low</option>
    <option value='PriceDesc'>low to high</option>
</select>

<!-- add this at the bottom of your page, just before </body> -->
<script src="js/jquery.min.js"></script>
<script>
    $('#sort').on('change', function () {
        $.post('sort.php', {sort: $(this).val()}, function (response) {
            $('#sort-ajax').html(response);
        });
    })
</script>

创建一个新的 PHP名为 sort.php 的文件,我们将发送我们的 AJAX调用此页面。

<?php
//Database connection
$db = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx')
or die('Error connecting to MySQL server.');

$query = "SELECT * FROM cs_shop";


if (!empty($_POST['sort']) && $_POST['sort'] == 'PriceAsc') {
    $query = "SELECT * FROM cs_shop ORDER BY price ASC";
} elseif (!empty($_POST['sort']) && $_POST['sort'] == 'PriceDesc') {
    $query = "SELECT * FROM cs_shop ORDER BY price DESC";
}

$result = mysqli_query($db, $query);


//loop start
while ($row = mysqli_fetch_array($result)) : ?>
    <div class="colm3">
        <div class="col3 r1">
            <div class="products-container">
                <h5><?= $row['product_name']; ?></h5>
                <a class="producy_img_link" href="#">
                    <img src="{$row[prod].prod_img}" style="width:auto; height:255px;">
                </a>
            </div>
        </div>

        <a href="#">
            <div class="block-right">
                <h6><?= $row['product_vintage']; ?></h6>
                <h5><?= $row['product_veriatel']; ?></h5>
                <div>
                    <span class="price">R <?= $row['product_price']; ?></span>
                </div>
            </div>
        </a>
    </div>

<?php endwhile;
mysqli_close($db);

关于javascript - 使用 php 或 javascript 过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44050184/

相关文章:

php - 如何防止取回我刚刚存储的值

php - 变量在 jquery 点击函数中没有改变

php - mysqli_fetch_object()期望参数1为mysqli_result…,并注意: undefined index :cart [duplicate]

mysql - 如何使用 codeigniter 连接 3 个表,表中没有任何空值?

javascript - 如何从一个对象解构并保留相同的对象?

php - WordPress 页面中的第二个 MySQL 数据库 PHP

javascript - 带有子句按钮的 Gridview 项目

php - 在类中使用 memcache

javascript - 通过 HTML 文本框查找某些子字符串,然后用其他字符串替换它们

javascript - 在 FullCalendar 上获取事件