Paul
Paul

Reputation: 3368

else statement logic not running

I have a database table called goals. By default a user does not have a record within this table and the only time they will is if a goal is created. I then have a progress bar which shows the progress of competition for the goals. The issue I was having originally is the values would be undefined, so I attempted to add logic to where it counts the rows and if it is greater than 0 it would send the adjusted variables, but if not it would send 0. For some reason it appears the if condition is always running. I believe that to be the case because it is attempting to run the division line of code:

$goal_completion_rate = $actual_status / $total_status ;
        $goal_completion_rate_percentage = round((float)$goal_completion_rate * 100) . '%';
        $result = array('total_goals' => $total_status, 'goals_completed' => $actual_status, 'completion_percentage' => $goal_completion_rate_percentage);

Here is the error:

<b>Warning</b>:  Division by zero in <b>/</b> on line <b>26</b><br />
{"total_goals":"0","goals_completed":null,"completion_percentage":"0%"}

Why isn't my else statement working so that I can get the users without records to show 0 as the figures?

Full code

$goal_total_sql = "
        SELECT sum(status) as sumna,
        COUNT(*) as cnt
        FROM goals
        WHERE user_id = ?
    ";
    $total_status = 0;
    $actual_status = 0;
    $goal_completion_rate_percentage = 0;
    $goal_count = 0;
    if ($goal_total_stmt = $con->prepare($goal_total_sql)) {
        $goal_total_stmt->execute(array($user_id));
        $rows = $goal_total_stmt->fetchAll(PDO::FETCH_ASSOC);
        $goal_count = $goal_total_stmt->rowCount();
        foreach ($rows as $row) {
            $actual_status = $row['sumna'];
            $total_status = $row['cnt'];
        }
    }
    if ($goal_count > 0) {
        $goal_completion_rate = $actual_status / $total_status ;
        $goal_completion_rate_percentage = round((float)$goal_completion_rate * 100) . '%';
        $result = array('total_goals' => $total_status, 'goals_completed' => $actual_status, 'completion_percentage' => $goal_completion_rate_percentage);
            echo json_encode($result);
    }
    else {
        $result = 0;
        echo json_encode($result);
    }

AJAX

function goalBar(){
        $.ajax({
                url: "ajax-php/goal-bar.php",
                type: "get",
                dataType : 'json',
                success: function (result) {
                  //console.log(result);
                    if (result == "Error!") {
                        alert("Unable to retrieve goal bar info!");
                        alert(result);
                    } else {
                        var total_goals = result.total_goals;
                        var goals_completed = result.goals_completed;
                        var goal_percent = result.completion_percentage;
                        var percent_symbol = '%';
                        $('#total-goals').html(total_goals);
                        $('#goals-completed').html(goals_completed);
                        $('#goal-percentage').html(goal_percent);
                        var bar = new ProgressBar.Circle('#goal-bar-container', {
                          color: '#aaa',
                          // This has to be the same size as the maximum width to
                          // prevent clipping
                          strokeWidth: 8,
                          trailWidth: 2,
                          easing: 'easeInOut',
                          duration: 1400,
                          text: {
                            autoStyleContainer: false
                          },
                          from: { color: '#aaa', width: 1 },
                          to: { color: '#38c', width: 6 },
                          // Set default step function for all animate calls
                          step: function(state, circle) {
                            circle.path.setAttribute('stroke', state.color);
                            circle.path.setAttribute('stroke-width', state.width);

                            var value = Math.round(circle.value() * 100);
                            if (value === 0) {
                              circle.setText('0');
                            } else {
                              circle.setText(value);
                            }

                          }
                        });
                        bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';
                        bar.text.style.fontSize = '2rem';

                        bar.animate(goals_completed/total_goals);  // Number from 0.0 to 1.0
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert(textStatus + " | " + errorThrown);
                    console.log("error"); //otherwise error if status code is other than 200.
                }
        });
    }   
    goalBar();

Upvotes: 0

Views: 77

Answers (1)

jmarkmurphy
jmarkmurphy

Reputation: 11493

Your sql will always return a single row. The aggregation functions ensure that. If there are no goals to report, the count(*) function will return a 0 in that row, and the sum() function will return a null. So $goal_count will always be 1, and really isn't the count of goal records for the user. The variable that actually holds the number of goal records is $total_status. You should be testing that rather than $goal_count.

Upvotes: 2

Related Questions