加入表并生成完整的百分比

时间:2014-10-15 12:12:53

标签: php sql ajax

2我有两张桌子; '目标'和共享goal_id的'activity'。目标有很多活动,活动是针对一个目标。活动表的状态只有3个可能的整数条目; 0(未启动),1(进行中),2(完成)。

我希望能够查询数据库,并创建百分比完整状态数字。

例如,如果1个目标有4个活动,其状态值为; 0,0,0,2。这表示目标已完成25%。进行中表示完成50%。

1 个答案:

答案 0 :(得分:0)

我最终想出来了......

<?php

require '../global/head.php'; 

function goalPercentage($goalid){
global $mysqli;

$activities = array();
$percentage = 0;

if ($result = $mysqli -> query("SELECT * FROM user_goal where goal_id='".$goalid."'")) {
    if($result -> num_rows > 0) {
        while ($row = $result -> fetch_object()) {
            global $mysqli;
            $goal_id = $row->goal_id;
            if ($results = $mysqli -> query("SELECT * FROM user_activity where goal_id='".$goalid."'")){

                if($results -> num_rows > 0) {
                    while ($row = $results -> fetch_object()) {
                        array_push($activities, $row->goal_id);

                        if($row->status == 0)
                        {
                            $percentage += 0;
                        }

                        else if($row->status == 1)
                        {
                            $percentage += 50;
                        }

                        else if ($row->status == 2)
                        {
                            $percentage += 100;
                        }

                    }
        }}

        else {
            return 0;
        }

        }
    } 


    else {
        echo "No Results to display :(";
    }}


//echo count($activities);
//echo $percentage;

$percentageResult = $percentage / count($activities);
//echo $result;
return round($percentageResult);
}
?>