我是php和sql的新手。今天,我给自己完成了从sql db获取整数值的任务,然后做了一些基本的计算。 还有其他地方可以在完成任务的同时减少代码,还是我已经达到了最基本的水平?我是否在执行过程中执行过任何操作?
我的目标是;
以下方式是我最好的尝试;
$con = new MySQLi('localhost', 'user', 'pass', 'db_test') ;
$count = $con->query('SELECT COUNT(SP$) FROM `math`');
$grp = $con->query('SELECT GROUP_CONCAT(SP$) FROM `math`');
$min = $con->query('SELECT MIN(SP$) FROM `math`');
$max = $con->query('SELECT MAX(SP$) FROM `math`');
$sum = $con->query('SELECT SUM(SP$) FROM `math`');
$avg = $con->query('SELECT AVG(SP$) FROM `math`');
$count = $count->fetch_assoc();
$grp = $grp->fetch_assoc();
$min = $min->fetch_assoc();
$max = $max->fetch_assoc();
$sum = $sum->fetch_assoc();
$avg = $avg->fetch_assoc();
$count = $count['COUNT(SP$)'];
$grp = $grp['GROUP_CONCAT(SP$)'];
$min = $min['MIN(SP$)'];
$max = $max['MAX(SP$)'];
$sum = $sum['SUM(SP$)'];
$avg = $avg['AVG(SP$)'];
显示和计算如下;
echo "Sample Size: " . $count ."</br />";
echo "Display Values:" . $grp ."</br />";
echo "Sum of Values: " . $sum ."</br />";
echo "Average: " . $avg ."</br /></br />";
echo "Now find the new average, by excluding the highest and lowest value:";
echo "Lowest Value: " . $min ."</br />";
echo "Highest Value: " . $max ."</br />";
echo "New Sum: " . ($sum - $max - $min) . "</br />";
echo "New Average : " . (($sum - $max - $min) / ($count-2));
答案 0 :(得分:0)
您可以尝试使用以下内容:
$con = new MySQLi('localhost', 'user', 'pass', 'db_test');
$operations = ["count"=>'COUNT(SP$)',
"grp"=>'GROUP_CONCAT(SP$)',
"min"=>'MIN(SP$)',
"max"=>'MAX(SP$)'...];
foreach($operations as $name=>$value){
$name = ${$name};
$name = $con->query('SELECT '.$value.' FROM `math`');
$name = $name->fetch_assoc();
$name = $name[$value];
}
做的是将所有操作放在一个关联数组(http://php.net/manual/en/language.types.array.php)中,并用foreach语句循环该数组。
现在,变量名称使用PHP Variables - Concatenate variable name组成。请注意,这不建议使用,但它存在且有效。
代码未经过测试,因为我的机器上没有安装PHP,但它应该有效。