1

I have searched around on forums however all answers don't seem to work for my I am guessing it's more user error.

What I am trying to do:

  1. Retrieve the data set from MySQL

  2. Count the total number of rows

  3. Work out specifically how many of them have the value "Y" in the metSLA column

  4. Work out specifically how many of them have the value "N" in the metSLA column

  5. Convert each of these metSLA values to a percentage

**The MySQL query works for sure and its stored in variable $result for reference.

*

        //sla and total case count and percentages
        $sla_met_rows = 0;
        $sla_not_met_rows = 0;

        $total_cases = mysql_num_rows($result);

        while ($row = mysql_fetch_array($result)) 
        {
        if `metSLA` = "Y"
            {
            $sla_met_rows ++;
            } else if `metSLA` = "N"
                {
                $sla_not_met_num_rows ++;
                }
        }
        $met_percentage = 100 / $total_cases * $sla_met_rows;
        $not_met_percentage = 100 / $total_cases * $sla_not_met_num_rows;
  • 1
    [Please, don't use `mysql_*` functions](http://stackoverflow.com/q/12859942/1190388) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the red box? Learn about prepared statements instead, and use [tag:PDO] or [tag:MySQLi]. – hjpotter92 Mar 29 '13 at 17:53
  • For reference - the MySQL data pull contains multiple columns and I cannot change this query. I believe the issue is likely to be on the if and else if lines as that is where it is erroring. However I don't know how to reference the mySQL column. – user2217666 Mar 29 '13 at 17:54

2 Answers2

5

You can use a single MySQL query to get the percentage result:

SELECT COUNT( CASE WHEN `metSLA` = "Y" THEN 1 ELSE NULL END ) AS `Yes`,
    COUNT( CASE WHEN `metSLA` = "N" THEN 1 ELSE NULL END ) AS `No`,
    COUNT(1) AS `total`
FROM `TableName`

In your PHP, it'll be referenced as:

$result = mysql_query( <<The query above is here>> );
$row = mysql_fetch_array( $result );
$met_precentage = $row['Yes'] * 100 / $row['total'];
$not_met_precentage = $row['No'] * 100 / $row['total'];
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
1

Change

    if `metSLA` = "Y"
        {
        $sla_met_rows ++;
        } else if `metSLA` = "N"
            {
            $sla_not_met_num_rows ++;
            }

To:

    if ($row['metSLA'] == "Y")
    {
      $sla_met_rows ++;
    }

    else if ($row['metSLA'] == "N")
    {
      $sla_not_met_num_rows ++;
    }

What you have has three problems:

  1. You're missing the brackets around the conditions,
  2. You're assigning (=) rather than comparing (==), and
  3. You're running a shell command rather than getting the value from the database row.
Michael
  • 11,912
  • 6
  • 49
  • 64