2

This is my code

<?php
Id  =$_GET['ID'];
error_reporting(0);
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ehealth monitoring", $con); 
$sth = mysql_query("SELECT DateandTime,BP FROM table  WHERE ID='".$Id."'");
$rows = array();
$rows['name'] = 'BP';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = [$r['DateandTime'],$r[eval('BP')]];
}
echo json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>

In this code BP contains 100/77, 100/50, 99/45 kind of values. I want convert this values as decimal. I can't find my mistake. please help me to convert the values and pass value to json.

Mild Milly
  • 111
  • 1
  • 10
  • You're evaluating the string `BP` to PHP code. Not the value, but the string. Did you mean to use `eval($r['BP'])`? Neither the less, simple split the string on a slash and do regular division rather than relying on EVAL. What happens when malicious data is in your database and gets eval'd in your source code? – h2ooooooo May 31 '15 at 11:41
  • thank you for your reply.i have no idea about eval.. just i tried. how can i convert the value if you have any code ??@h2ooooooo – Mild Milly May 31 '15 at 11:44
  • You know the value is going to be `number/number`. Split with `$fractions = explode('/', $r['BP'])` and calculate it like `$fractions[0] / $fractions[1]`. Also note that your code is using an outdated `mysql` library (use `mysqli_` or `PDO`) and your code is open to SQL injection (you need to escape or bind your variables). – h2ooooooo May 31 '15 at 11:44
  • thank you sir for your idea @h2ooooooo – Mild Milly May 31 '15 at 11:51
  • @h2ooooooo thank sir its works – Mild Milly May 31 '15 at 12:45
  • See accepted asnwer here: https://stackoverflow.com/questions/1954018/php-convert-decimal-into-fraction-and-back/1954030 – cooler Oct 25 '19 at 16:57

2 Answers2

5

This function will help you, feel free to modify the function as per your need.

   <?php
    echo convertToDecimal ("100/77");

    function convertToDecimal ($fraction)
    {
        $numbers=explode("/",$fraction);
        return round($numbers[0]/$numbers[1],6);
    }
    ?>

This function will convert fraction to decimal.

user1735921
  • 1,359
  • 1
  • 21
  • 46
0

A small extension to the function above:

<?php
echo convertToDecimal ("100/77/22");
function convertToDecimal($sFraction, $iPrecision = 6, $sFractionSign = '/')
{
    $aNumbers = explode($sFractionSign, $sFraction);
    $fResult = $aNumbers[0];
    //user wrote a fraction with at least one $sFractionSign
    if (count($aNumbers) != 1) {
        array_shift($aNumbers);
        foreach ($aNumbers as $iNumber) {
            $fResult /= $iNumber;
        }
    }
    return round($fResult, $iPrecision);
}
Tofandel
  • 3,006
  • 1
  • 29
  • 48