simple computation of mysql sums & php. How to do?

74 views Asked by At

I need to do a computation within my website. I have all parameters but couldn't figure out how to combine them to one result.

Please help me to solute this!

I get the data from mysql database: (shorted)

   <?php
     $res = mysql_query('SELECT SUM(status) FROM ' . 'success_rate', $con);
        if ($row = mysql_fetch_array($res, MYSQL_NUM))
        {
           $rate = trim($row[0]);    ?>

<?php
    $res = mysql_query('SELECT Count(*) FROM ' . 'user_registration', $con);
        ?>

So i get 2 classic params

What I need is to have just one Number in the end. This is how the computation shall work:

((<?= $status ?> / <?= $2nd ?>)*100)-200   =  result

Would appreciate your help.

3

There are 3 answers

0
Ramsay Smith On

There are a few problems. First, the mysql extension is depreciated. Use mysqli instead. When you do that you change mysql_fetch_array($res, MYSQL_NUM) to mysqli_fetch_array($res).

Next, you need to close the if statement brackets. You only have an opening bracket.

That second code snippet is a syntax errpr. Do this: $result = (($status / $second)*100)-200

Beyond that, I don't know what else you want because you haven't given enough detail.

0
vaso123 On

You need to fetch the second query also:

$rate = 0;
$count = 0;

$res = mysql_query('SELECT SUM(status) FROM success_rate', $con);
$row = mysql_fetch_array($res);
$rate = $row[0];

$res = mysql_query('SELECT Count(*) FROM user_registration', $con);
$row = mysql_fetch_array($res);
$count = $row[0];

if ($count != 0) {
    echo (($status / $count) * 100) - 200;
} else {
    echo 'Count was 0';
}
  • Do not use mysql functions because the are deprecated. Use mysqli or PDO instead.

  • Use an IDE to inspect your syntax errors in your code.

0
peixotorms On

If you want to shorten the code by returning the result with one query, you could do it this way:

$res = mysql_query("SELECT (((SUM(status) / (SELECT Count(*) FROM user_registration)) * 100) - 200) as result FROM success_rate") or die (mysql_error());

Note however: if the second parameter is smaller than the first, you will get a negative number in the end, because you're subtracting 200 in the end.

For example: IF SUM(status) = 10 AND Count(*) = 100, THEN your result is -190

((10/100)*100)-200 = -190