2

Am creating an ecommerce project for a client who wants to sell groceries online

and am having a price column which will contain comma separated price of the product for the respective quantity. The problem is how I can give sort by 'price high to low' or 'price low to high' feature.

This is the example table

    **id**    **Price**         **Quantity**           Name
       1          20,30,50         250mlgm,500ml,1lt     Coca-Cola
       2          40,60,70         250mlgm,500ml,1lt     Pepsi

Now the question is what the query would look like if I want to sort the price column from low to high or high to low

ORDER BY Price DESC or ORDER BY Price ASC doesn't work in my case

Please guide me on this

Am populating the price and quantity of each product in select tag by exploding the commas and saving them in an array like this

 <select ><option style='font-size:1vw;' value="Select Unit" >Select Unit</option>  

  <?php
 $drq=$rows['Quantity'];
$drp=$rows['Price'];
  $degh=explode(',',$drp);
 $tryGH=explode(',',$drq);
  for($ij=0;$ij<count($tryGH);$ij++){
 echo "<option style='font-size:1vw;' value=$degh[$ij]  >$tryGH[$ij]&nbsp;-&nbsp;$degh[$ij]</option>";  
  }
  ?> </select>

the result looks like this

enter image description here

user3225075
  • 373
  • 1
  • 5
  • 23
  • You can't because the values are strings, not integers. You could do it in PHP later. Why not store the price and quantity as individual pairings (e.g. have 9 rows above)? – chris85 Apr 12 '15 at 13:47
  • aint gona happen, u need to make many to many table for price and quantity with id as FK – Abdul Rehman Apr 12 '15 at 13:48
  • Hmmm.. different rows for respective quantities for a singe product will result an lengthy table.. I think i must remove sort by feature for items with variable price for variable quantities – user3225075 Apr 12 '15 at 13:54
  • Why do you care how large the table is? – chris85 Apr 12 '15 at 14:03
  • actually am populating quantity and price in a select tag by separating commas so that the end user can see the quantity and the respective price of the product at a time. I thought that would be convenient. Is there any simple solution to carry out the same? – user3225075 Apr 12 '15 at 14:21
  • There should be, can you post what you have? – chris85 Apr 12 '15 at 14:22
  • $drq=$rows['Quantity']; $drp=$rows['Price']; $degh=explode(',',$drp); $tryGH=explode(',',$drq); for($ij=0;$ij$tryGH[$ij] - $degh[$ij]"; } this is how am separating each value and populating in a select tag – user3225075 Apr 12 '15 at 14:26
  • Can you edit your question with your full code? – chris85 Apr 12 '15 at 14:31
  • have edited my question please have a look – user3225075 Apr 12 '15 at 14:44
  • Normalize your tables. The problem is that you stored lists of values as strings. – 1010 Apr 12 '15 at 15:16
  • Stop [SQL Jaywalking](http://stackoverflow.com/questions/738133/comma-separated-values-in-a-database-field) first; the solution will follow almost directly from that. – Ja͢ck Apr 14 '15 at 03:42

2 Answers2

1

Try using convert to convert the string to number and then sort it

SELECT id, Price, Quantity FROM Products ORDER BY CONVERT(Price, UNSIGNED INTEGER) ASC
littleibex
  • 1,705
  • 2
  • 14
  • 35
  • 1
    How would this work? There are multiple values there. – chris85 Apr 12 '15 at 14:00
  • I tried it in my test project and it worked. The prices are entered corresponding to the quantity. Hence, if I can just sort it by the first value of the price then the result should be correct. CONVERT converts the string to a number so '20,30,50' is converted to 20 and based on this the sorting occurs. – littleibex Apr 12 '15 at 14:03
  • Yea, there are 3 prices though `20`, `30`, and `50`, for 3 quantities. – chris85 Apr 12 '15 at 14:05
  • Yes, I am aware of that. But, as I said earlier the prices are entered corresponding to the quantity. So, product 1 has a price of 20 for 25gm, 30 for 50gm and so on. That means, products 1, 2 and 3 have prices 20, 40 and 5 respectively for 25gm quantity. If I assume 25gm here as a unit and sort the - 20, 40 and 5 - then that should give me the correct result – littleibex Apr 12 '15 at 14:10
  • What if a product only comes in `1gm` quantity or `500gm` quantity? You'll be comparing `25gm` prices to `1gm` prices or `500gm` prices. Also what if the large quantitied product (`50gm` and `100gm`) were cheaper for some reason? – chris85 Apr 12 '15 at 14:17
  • "What if a product only comes in 1gm quantity or 500gm quantity?" - In that case my query won't work. "what if the large quantitied product (50gm and 100gm) were cheaper for some reason?" - then the sorting would be anyways impossible because I believe the OP wants to sort the products from cheapest to costliest or vice-versa and not the products per quantity. – littleibex Apr 12 '15 at 14:22
  • Yes, too many presumptions. The DB is structured wrong, this "answer" isn't the answer. The task can't be completed as currently structured. – chris85 Apr 12 '15 at 14:25
1

You could arrange your DB a few ways. One way would be

**id**    **Price**         **Quantity**           Name
       1          20         250mlgm            Coca-Cola
       2          30         500ml              Coca-Cola 
       3          50         1lt                Coca-Cola

Then in your code you could output to the client to select the value with

<select name="unit" >
    <option style='font-size:1vw;' value="Select Unit" >Select Unit</option>
<?php
$query = 'select Quantity, Price, Id, Name from Products ORDER BY name asc, Price DESC';
//execute the query, I don't know your driver
while($row = FETCH_FROM_YOUR_DRIVER) {
    $quantitY = $row['Quantity'];
    $price = $row['Price'];
    $id = $row['Id'];
    $company = $row['Name'];
    echo "<option style='font-size:1vw;' value='$id'>$quantity&nbsp;-&nbsp;$price&nbsp;$company</option>";  
}?>
</select>

Then you should take the ID they select and query the price from your DB. In your current code I think you are taking the price directly from the client. The client however could manipulate that and send you a price of 0.

Update:

<style type="text/css">
.container {
    display:block;
    float:left;
    margin:15px;
}
</style>
<?php
$query = 'select Quantity, Price, Id, Name from Products ORDER BY name asc, Price DESC';
//execute the query, I don't know your driver
$count = 0;
while($row = FETCH_FROM_YOUR_DRIVER /*again not sure of your driver*/) {
    $products[$count]['id'] = $row['Id'];
    $products[$count]['price'] = $row['Price'];
    $products[$count]['quantity'] = $row['Quantity'];
    $products[$count]['name'] = $row['Name'];
    $count++;
}
/* Can be removed, I haven't set up a DB so this is how I test
$products = array(array('id' => 2, 'price' => 30, 'quantity' => '500ml', 'name' => 'Coca-Cola'),
            array('id' => 3, 'price' => 50, 'quantity' => '1lt', 'name' => 'Coca-Cola'),
            array('id' => 4, 'price' => 20, 'quantity' => '25mlgm', 'name' => 'Pepsi'),
            array('id' => 5, 'price' => 30, 'quantity' => '500ml', 'name' => 'Pepsi'),
            array('id' => 6, 'price' => 50, 'quantity' => '1lt', 'name' => 'Pepsi'));
*/
$sameproduct = false;
foreach($products as $key => $product) { 
    if ($key == 0 || $products[($key - 1)]['name'] != $product['name']) { 
        if ($key != 0) { ?> 
            </select>
            </div>
        <?php } ?>
    <div class="container">
        <h4><?php echo $product['name'];?></h4>
        <img src="/images/LOCATION/<?php echo strtolower(str_replace(array(' ', '-'), '_', $product['name']));?>.jpg" /> <br />
    <select name="unit" >
    <?php } ?>
        <option style='font-size:1vw;' value='<?php echo $product['id'];?>'><?php echo $product['quantity'];?> - <?php echo $product['price'];?></option>
<?php } ?>

This requires your names are consistent and also assumes the name in the db matches the name of the image in your file system. It replaces spaces and dashes in the name with underscores.

chris85
  • 23,846
  • 7
  • 34
  • 51
  • Ok, but how will I query to populate quantity and price of a same item at one place. As per your answer I think the user will get just one quantity and price to select from .. how to prevent that? extending a table is ok but confusing an end user doesn't seem ok to me. what would be your suggestion on that? by the way what is FETCH_FROM_DRIVER .. i have No idea on that but i do a cross checking to verify price and quantity – user3225075 Apr 12 '15 at 18:04
  • How about the update above, make sense? The "FETCH_FROM_DRIVER" means I don't know what driver you are using but you will need to fetch the data by the function associated with whichever driver you are using. You haven't posted your full code so I don't know how you're accessing DB. – chris85 Apr 13 '15 at 01:49
  • But, how do I sort products as per price as am populating price and quantity in a select tag and there will be multiple products with diferent quantity and respective prices – user3225075 Apr 13 '15 at 09:34
  • That should be sorting by name first so all your coke products will be together then by price. Can you give an example of what you want the output to be? If you just want it to be just by price then remove the `name asc, `. – chris85 Apr 13 '15 at 12:25
  • have edited my question and added an snapshot please have a look – user3225075 Apr 13 '15 at 20:18
  • it displays as different products not checking for same product. – user3225075 Apr 14 '15 at 10:18
  • I forgot to increment `$count`. Can you check now and if they're separate output `$products`. – chris85 Apr 14 '15 at 10:46
  • with that edit i got all the products price and quantity in one select tag – user3225075 Apr 14 '15 at 12:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75194/discussion-between-chris85-and-user3225075). – chris85 Apr 14 '15 at 12:20