我正在以这种方式计算一个参数(X):
<?php
$link=mysql_connect("localhost","root","");
mysql_select_db("hand");
$result = mysql_query("select * from sessions",$link);
$num_calls = mysql_num_rows($result);
echo '<br/>'."\n Total X :\n $num_calls ".'<br/>';
?>
我正在以这种方式计算另一个参数(Y):
<?php
mysql_connect("localhost","root","");
mysql_select_db("hand");
$result = mysql_query("SELECT * FROM cars WHERE start_at > TIMESTAMPADD(WEEK, -4, CURDATE()) AND TIMESTAMPDIFF(MINUTE, start_at, end_at) > 5");
$num_rows = mysql_num_rows($result);
echo '<br/>'."\n Total Y :\n $num_rows ".'<br/>';
?>
在另一个地方,我需要计算X / Y的比例。我该怎么做,因为它需要在同一个html页面的另一个字段中完成。
答案 0 :(得分:3)
你这样做:
$num_calls = intval($num_calls); // Make sure these are integers
$num_rows = intval($num_rows);
$calculation = $num_calls / $num_rows;
echo $calculation;
答案 1 :(得分:1)
好的,我认为我理解。
你想要X:Y,其中X是与Y的比率:
$link=mysql_connect("localhost","root","");
mysql_select_db("hand");
$result = mysql_query("select * from sessions",$link);
$num_calls_x = mysql_num_rows($result);
$result = mysql_query("SELECT * FROM cars WHERE start_at > TIMESTAMPADD(WEEK, -4, CURDATE()) AND TIMESTAMPDIFF(MINUTE, start_at, end_at) > 5");
$num_calls_y = mysql_num_rows($result);
echo '<br/>'."\n Total X :\n $num_calls_x ".'<br/>';
echo '<br/>'."\n Total Y :\n $num_calls_y ".'<br/>';
echo 'Ratio: '.round(($num_calls_x/ $num_calls_y) * 100, 0);
答案 2 :(得分:1)
嗯 首先,这是一种非常昂贵的计算方法。
Select Count(*) from Sessions
和
Select Count(*) from Cars...
类似
Select Cast(Select Count(*) From Sessions) as FLOAT) / (Select Count(*) From Cars...)
应该让你亲近。
然后你不需要费心去坚持它,不过如果你坚持,所有通常的机制都适用。
答案 3 :(得分:1)
你可以把查询字符串放到这样的数组中:
$queryArray = array("select * from sessions", "SELECT * FROM cars WHERE start_at >
TIMESTAMPADD(WEEK, -4, CURDATE()) AND TIMESTAMPDIFF(MINUTE, start_at, end_at) > 5");
只使用一次foreach:
foreach($query in $queryArray)
{
$result = mysql_query($query);
$count = mysql_count($result);
$countList[] = $count
}
$number = 0;
现在你需要用另一个foreach来计算项目中的比例
foreach($number in $countList)
{<br/>
$number = $number + $number;
}<br/>
$ratio = $number / count($countList);
像这样,您可以将所有未来的查询添加为字符串,一切都将继续有效。
P.S。我目前无法测试代码,但它应该非常实用。不太确定foreach as。
答案 4 :(得分:-1)
您可以将此值放入会话/ cookie并在其他位置读取。