2012-09-23 117 views
1

我想從另一個PHP變量的百分比,例如我有兩個數據庫的信息,第一個數據庫充滿了不明身份的信息。第二個數據庫充滿了我們已經確定的信息。所以我想動態地計算出所有信息的百分比。從另一個PHP變量獲取一個百分比

下面是一個PHP函數來制定出一個百分比,

//TOTAL ENTRIES INTO Table 1 FOR total data 
$result = mysql_query("SELECT * FROM table1"); 
$num_total = mysql_num_rows($result); 

//TOTAL ENTRIES IN Table 2 FOR THE PERCENTAGE 
$result = mysql_query("SELECT * FROM table2"); 
$num_amount = mysql_num_rows($result); 

function percent($num_amount, $num_total) { 
$count1 = $num_amount/$num_total; 
$count2 = $count1 * 100; 
$count3 = 100 - $count2; 
$count = number_format($count3, 0); 
echo $count; 
} 

兩個查詢返回數據庫中的數行總數的正確的信息,但是計數變量不返回任何信息。

任何意見或建議,將不勝感激。

感謝

斯坦

+0

如果你不打算使用查詢的結果,你應該改爲'SELECT COUNT(*)FROM table;'。 –

+2

爲什麼你需要'$ count3 = 100 - $ count2;'??? '$ count2 = $ count1 * 100;'給你的百分比 – Baba

回答

6

您迴應的結果,但你不從函數返回。這可能是問題所在。

但是,你能做到的百分比計算所有SQL:

SELECT 100*(SELECT COUNT(*) FROM table1)/(SELECT COUNT(*) FROM table2) 
    AS percent; 

否則,

function percent($num, $total) 
{ 
    return number_format((100.0*$num)/$total, 2); 
} 
+0

謝謝,直接在SQl中做它使得它變得容易很多,非常感謝。 –

1

我的猜測是,這樣的事情或許應該工作(請注意,我沒有測試這可能需要調整):

<?php 

//TOTAL ENTRIES INTO Table 1 FOR total data 
$result = mysql_query("SELECT COUNT(*) AS total FROM table1"); 
$table1_total = mysql_result($result, 0); 

//TOTAL ENTRIES IN Table 2 FOR THE PERCENTAGE 
$result2 = mysql_query("SELECT COUNT(*) AS total FROM table2"); 
$table2_total = mysql_result($result2, 0); 

function percent($num_amount, $num_total) { 
    $count1 = $num_amount/$num_total; 
    $count2 = $count1 * 100; 
    $count3 = 100 - $count2; 
    $count = number_format($count3, 0); 
    echo $count; 
} 

percent($table1_total, $table2_total); 
0

試試這個:

<?php 

    function percent($num_amount, $num_total) { 
    $count1 = $num_amount/$num_total; 
    $count2 = $count1 * 100; 
    $count = number_format($count2, 0); 
    echo $count2."<br>"; 
    } 

    percent(50,100); 
    percent(13,100); 
    percent(13,200); 

    ?> 
相關問題