Jump to content

Evaluating variables stored inside an array variable and re-sorting that array according to the evaluated values?


champbronc2

Recommended Posts

So I have a MySQL database table that stores order ID and prices. The price can either be dynamic or static. 

 

So for example:

 

Order ID | Price

 

1|205.99

 

2|215.95

 

3|217.88

 

4|$marketrate

 

5|$marketrate*1.02

 

6|212.99

 

 

On my php page I have

 



    include "prices.php";
    $sql="Select `Order ID`, `Price` from `table` ORDERBY `price`";
    $result=mysql_query($sql);
    
    while($row = mysql_fetch_assoc($result)){


echo "<tr ".$tr_class.">\n";
foreach ($row as $field=>$value) {




eval('$value = ' . $value . ';');
echo "<td>" . $value . "</td>\n";


}
echo "</tr>\n";






}


 

So you see I use eval() to evaluate the price variable and display it and prices.php defines all the prices like $marketrate and whatnot.

 

My question is, how can I orderby the evaluated prices? When I use orderby in my mysql statement, it sorts the array based on static numbers and then the variable names $marketrate, which obviously is wrong because $marketrate is not a number. I need it to sort the array according to what the evaluated value of $marketrate is.

 

**Is it possible to somehow evaluate all the variables in the $result array, and then re-sort the array using a PHP sorting function?**

 

edit: tried to put eval('$result['Price'] = ' . $result['Price'] . ';'); in there but it did not work.

 

My question is, how can I orderby the evaluated prices? When I use orderby in my mysql statement, it sorts the array based on static numbers and then the variable names $marketrate, which obviously is wrong because $marketrate is not a number.

MySQL does not sort arrays. It sorts the data that is returned from your query criteria. Only until your use msyq_fetch_* function it converts the data into a format that is usable by PHP,  in your case an array.

 

You should be very careful when using eval it could become to major security issue if you do not handle it correctly.

 

What you could do is change your query to this

$sql="SELECT  `Order ID`, REPLACE(`Price`, '$marketrate', $marketrate) as MarketPrice from `table` ORDERBY MarketPrice";

This will replace $marketrate in Price field to the value of the $marketrate variable. And then it'll sort the results by MarketPrice. However I don't think it'll also perform mathematical sums too like $marketrate*1.02.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.