我有一個表格名稱爲「Table1」的學生以下記錄。如何打印出所有班級的結果
student_id | Name | Math | English | Sience | Class
1 John 100 90 89 std two
2 Simon 100 100 100 std two
3 Irene 80 70 70 std two
我試着輸出每個學生passmark的AVG,Total,但我沒有把所有班級的結果都輸出。
例如:現在結果是這樣的,當我搜索。
student_id | Name | Math | English | Sience | Class Average Total
1 John 100 90 89 std two 93 279
,當我尋找另一名學生,我得到了想要的答案,但是當我搜索「STD兩個」作爲類的名字,我得到誰擁有1個student_id數據,而不是所有類第一個學生的結果。 我想要的答案是這樣或任何格式,但應輸出所有類的結果。
student_id | Name | Math | English | Sience | Class Average Total
1 John 100 90 89 std two 93 279
student_id | Name | Math | English | Sience | Class Average Total
2 Simon 100 100 100 std two 100 300
student_id | Name | Math | English | Sience | Class Average Total
3 Irene 80 70 70 std two 73.3 220
這是我的PHP代碼
<?php
//include mysql connect
$query='query';
if (isset($_GET['query']))
{
$query=$_GET['query'];
}
$min_length = 2;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum
length
then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT *, AVG(math+english+science)/3 as
Average, (math+english+science)as Total from table1
WHERE (`name` LIKE '%".$query."%') or (`class` LIKE '%".$query."%')") or
die(mysql_error());
// '%$query%' is what we're looking for, % means anything, for example if $query
is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use
`title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %'
...OR ... '$query %' ... OR ... '% $query'
if(strlen($query) >= $min_length){
// if query length is more or equal minimum length the
if(mysql_num_rows($raw_results) >= 0){
// if one or more rows are returned do following
// $results = mysql_fetch_array($raw_results) puts data from database into
array, while it's valid it does the loop
while($results = mysql_fetch_array($raw_results)){
//The echo table
echo "<table width='500' height='2' cellpadding='2' cellspacing='0' border='0'>";
echo"<tr><td>Id_number</td><td>Name</td><td>Math</td><td>English</td><td>Science</td>
<td>Class</td><td>Average</td><td>Total</td>";
echo "<tr>"."<td>".$results["student_id"]."</td>"."<td>".$results["name"]."</td>"."
<td>".$results["math"]."</td>"."<td>".$results["english"]."</td>"."
<td>".$results["science"]."<td>".$results["class"]."<td>".$results["Average"]."</td>"."
<td>".$results["Total"]."</td>"."</p>";
echo"</table>";
}
}
}
}
?>
不要調用'AVG'。這是爲了跨行平均,而不是跨列平均。把總數除以3即爲平均值。 – Barmar
[** Sample **](http://sqlfiddle.com/#!2/e18bc1/4/1)。 [AVG做什麼?](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_avg) – Prix
順便說一下,您可能想要將'更改爲'<?php'實際上讓我重述那個;你會想改變這一點。 –