简体   繁体   中英

How to do sorting of records fetched from MySQL database using PHP?

I am writing an advance searching code for my site. I want to do sorting of records that are fetched from MySQL database based on 4 parameters - Customer Name, Company Name, Order Quantity and Total Order Value. The searching is working pretty good and also the sorting of values based on Customer Name and Company Name. But the problem is that I am not able to sort the rows based on Order Quantity and Total Order Value.

First see the interface of my task -

在此处输入图片说明

I am using 4 tables to accomplish this search engine with sorting. Here are the tables:

  1. address_book table:

在此处输入图片说明

  1. customers table:

在此处输入图片说明

  1. orders table:

在此处输入图片说明

  1. orders_products table:

在此处输入图片说明

And here is my PHP code to do searching and sorting:

<?php
require_once 'includes/config.php';
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css"
      href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.css">
<script type="text/javascript">
    $(document).ready(function () {
        //$("#datepicker").datepicker();
        $("#txtstartdate").datepicker({
            dateFormat: "yy-mm-dd",
        });
        $("#txtenddate").datepicker({
            dateFormat: "yy-mm-dd",
        });
    });
</script>
<div>
    <form name="frm1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <table width="100%" border="0" align="center">
            <tr>
                <th>Start Date:</th>
                <td><input type="text" name="txtstartdate" id="txtstartdate"
                           value="<?php if (isset($_POST['btnsearch'])) {
                               echo $_POST['txtstartdate'];
                           }
                           else {
                               echo '';
                           } ?>"/></td>
            </tr>
            <tr>
                <th>End Date:</th>
                <td><input type="text" name="txtenddate" id="txtenddate"
                           value="<?php if (isset($_POST['btnsearch'])) {
                               echo $_POST['txtenddate'];
                           }
                           else {
                               echo '';
                           } ?>"/></td>
            </tr>
            <tr>
                <th>Customer Name:</th>
                <td><input type="text" name="txtcustomername" id="txtcustomername"
                           value="<?php if (isset($_POST['btnsearch'])) {
                               echo $_POST['txtcustomername'];
                           }
                           else {
                               echo '';
                           } ?>"/></td>
            </tr>
            <tr>
                <th>Company Name:</th>
                <td><input type="text" name="txtcompanyname" id="txtcompanyname"
                           value="<?php if (isset($_POST['btnsearch'])) {
                               echo $_POST['txtcompanyname'];
                           }
                           else {
                               echo '';
                           } ?>"/></td>
            </tr>
            <tr>
                <th>Sorting:</th>
                <td><select name="selsorting" id="selsorting">
                        <option
                            value='customer_name' <?php if (isset($_POST['btnsearch']) && $_POST['selsorting'] == 'customer_name') {
                            echo "selected='selected'";
                        } ?>>
                            Customer Name
                        </option>
                        <option
                            value="company_name" <?php if (isset($_POST['btnsearch']) && $_POST['selsorting'] == 'company_name') {
                            echo "selected='selected'";
                        } ?>>
                            Company Name
                        </option>
                        <option
                            value="order_quantity" <?php if (isset($_POST['btnsearch']) && $_POST['selsorting'] == 'order_quantity') {
                            echo "selected='selected'";
                        } ?>>
                            Order Quantity
                        </option>
                        <option
                            value="total_order_value" <?php if (isset($_POST['btnsearch']) && $_POST['selsorting'] == 'total_order_value') {
                            echo "selected='selected'";
                        } ?>>
                            Total Order Value
                        </option>
                    </select></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="btnsearch" value="Search"/>
            </tr>
        </table>
    </form>
</div>
<?php
if (isset($_POST['btnsearch'])) {
    $where = array();

    if (isset($_POST['txtstartdate']) && !empty($_POST['txtstartdate'])) {
        $startdate = $_POST['txtstartdate'];
        $where[]   = " orders.date_purchased >= '$startdate' ";
    }
    if (isset($_POST['txtenddate']) && !empty($_POST['txtenddate'])) {
        $enddate = $_POST['txtenddate'];
        $where[] = " orders.date_purchased <= '$enddate' ";
    }
    if (isset($_POST['txtcustomername']) && !empty($_POST['txtcustomername'])) {
        $customername = $_POST['txtcustomername'];
        $where[]      = " customers.customers_firstname LIKE '%$customername%' or customers.customers_lastname LIKE '%$customername%' ";
    }
    if (isset($_POST['txtcompanyname']) && !empty($_POST['txtcompanyname'])) {
        $companyname = $_POST['txtcompanyname'];
        $where[]     = " address_book.entry_company LIKE '%$companyname%' ";
    }
    if (isset($_POST['selsorting'])) {
        $sorting = $_POST['selsorting'];
        $where[] = " 1 = 1 GROUP BY customers.customers_id ORDER BY $sorting ";
    }

    if (count($where) > 0) {
        $query['where'] = " WHERE " . implode(" AND ", $where);
    }

    $sql = "SELECT customers.customers_id, CONCAT(customers.customers_firstname, ' ', customers.customers_lastname) AS `customer_name`, address_book.entry_company AS `company_name`, orders_products.final_price AS total_order_value
    FROM customers
    LEFT JOIN orders ON orders.customers_id = customers.customers_id
    LEFT JOIN address_book ON address_book.customers_id = customers.customers_id
    LEFT JOIN orders_products ON orders_products.orders_id = orders.orders_id " . $query['where'];

    $rs = mysql_query($sql);
    echo "<table width='100%' align='center' border='1' cellpadding='5' cellspacing='0'>";
    echo "<tr><th>Customer ID</th><th>Customer Name</th><th>Company Name</th><th>Order Quantity</th><th>Order Total</th></tr>";
    while ($row = mysql_fetch_array($rs)) {
        $sql2 = "SELECT COUNT(*) AS 'quantity' FROM `orders` WHERE `customers_id` = " . $row['customers_id'];
        $rs2  = mysql_query($sql2);
        while ($row2 = mysql_fetch_array($rs2)) {
            $sql3 = "SELECT SUM(`final_price`) AS 'total_order_value' FROM `orders_products` WHERE `orders_id` IN (SELECT `orders_id` FROM `orders` WHERE `customers_id` = " . $row['customers_id'] . ")";
            $rs3  = mysql_query($sql3);
            while ($row3 = mysql_fetch_array($rs3)) {
                echo "<tr><td>&nbsp;" . $row['customers_id'] . "</td>";
                echo "<td>&nbsp;" . $row['customer_name'] . "</td>";
                echo "<td>&nbsp;" . $row['company_name'] . "</td>";
                echo "<td>&nbsp;" . $row2['quantity'] . "</td>";
                echo "<td>&nbsp;" . $row3['total_order_value'] . "</td></tr>";
            }
        }
    }
    echo "</table>";
}
?>

I am not understanding how to do sorting on order quantity and total order value as they are not in the main left join query and they are generated on the fly. If I use the aggregate functions COUNT and SUM for calculating the order quantity and total order value in the main left join query then the results are not getting accurate. But if I calculate these in the inner queries then i dont understand how to do sorting based on these two parameters.

Andy help will be greatly appreciated.

Thanks in advance.

您应该使用array_multisort()数组函数对多维数组进行排序。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM