// MySQL Query gets the distinct Schools in database
// The distinct schools are then stored in an array called $allSchools
$sllSchoolsQuery = "SELECT DISTINCT stud_school AS schools FROM students";
$schoolNames = mysqli_query($conn, $sllSchoolsQuery);
while ($row = mysqli_fetch_assoc($schoolNames)) {
$arraySkl[] = $row['schools'];
}
var_dump($arraySkl);
echo "<br>";
// This will loop through the associative array called $arraySkl
foreach($arraySkl as $allSchools) {
}
上面的代码显示了一个查询,该查询在名为stud_school
的表中从列students
(包含学校名称)中获取不同的值。然后将查询结果(不同的学校名称)存储在名为$arraySkl
的数组中。然后我使用foreach
循环遍历数组($arraySkl
)。
我也有一个功能:
// FUNCTION which calculates the sum of the boys and girls for each school
function bgTotSkl($bgTotSkl_SchoolName, $conn) {
// This if statement prevents SQL injection
if(isset($bgTotSkl_SchoolName)){
$bgTotSkl_SchoolName = mysqli_real_escape_string($conn,$bgTotSkl_SchoolName);
}
// Query called $bgTotSkl_Query, uses php variable called $bgTotSkl_SchoolName inorder
// to provide an input to specify a specific school
$bgTotSkl_Query = "SELECT SUM(result_studpoints) AS totalbg, stud_gender
FROM result
JOIN students ON result.stud_id WHERE result.stud_id = students.stud_id
AND stud_school = '$bgTotSkl_SchoolName'
GROUP BY stud_gender";
$mainQuery = mysqli_query($conn, $bgTotSkl_Query);
// Above $mainQuery executes query and stores the results as a table called $mainQuery
// $data stores the results of the query for each line within while loop
while ($data = mysqli_fetch_assoc($mainQuery)) {
echo "Total $bgTotSkl_SchoolName " . $data['stud_gender'] . ": " . $data['totalbg'] . "<br>";
}
}
上面的函数包含另一个完美正常的mysql查询。
我遇到的问题是我想执行foreach循环的结果,其中包含学校名称到函数的参数中,这样就可以单独输入每个学校名称作为参数并使用学校名称而在数组中:
// Executing function
bgTotSkl($allSchools, $conn);
但问题是我没有从这个命令得到任何输出。
答案 0 :(得分:0)
试
function bgTotSkl($bgTotSkl_Mixed, $conn) {
!is_array($bgTotSkl_Mixed) AND $bgTotSkl_Mixed=array($bgTotSkl_Mixed);
foreach($bgTotSkl_Mixed as $bgTotSkl_SchoolName){
if(isset($bgTotSkl_SchoolName)){
$bgTotSkl_SchoolName = mysqli_real_escape_string($conn,$bgTotSkl_SchoolName);
}
$bgTotSkl_Query = "SELECT SUM(result_studpoints) AS totalbg, stud_gender
FROM result
JOIN students ON result.stud_id WHERE result.stud_id = students.stud_id
AND stud_school = '$bgTotSkl_SchoolName'
GROUP BY stud_gender";
$mainQuery = mysqli_query($conn, $bgTotSkl_Query);
while ($data = mysqli_fetch_assoc($mainQuery)) {
echo "Total $bgTotSkl_SchoolName " . $data['stud_gender']
. ": " . $data['totalbg'] . "<br>";
}
}
}