Average of horizontals data mysql php - php

I hope you are doing well. I am working in a school management project , i want to get the average of 5 test(devoir) of each subject(Matiere) like-
i tried to use AVG() inside while loop of getting horizontale devoir data, i got no result ,any suggestions ??
$query5 = "select * from devoir where CIN_ELEVE = '$cinE' and ID_ELV_AN_CLS = $select2 GROUP BY MODULE_DEVOIR";
$result5 = mysqli_query($con,$query5);
if(mysqli_num_rows($result5)>0)
{
echo"<table class='table table-bordered table-striped table-hover table-info'><tr>
<th>MATIERE</th>
<th>devoir1</th>
<th>devoir2</th>
<th>devoir3</th>
<th>devoir4</th>
<th>devoir5</th>
<th>AVG</th>
</tr>
";
while($rows = mysqli_fetch_assoc($result5))
{
$moduleD = $rows['MODULE_DEVOIR'];
$queryDEV = "select * from devoir inner join eleve on devoir.CIN_ELEVE = eleve.CIN_ELEVE where eleve.CIN_ELEVE = '$cinE' and MODULE_DEVOIR = '$moduleD' order by MODULE_DEVOIR";
$resultDEV = mysqli_query($con,$queryDEV);
/*to print subject name*/
echo"<tr><td>$moduleD</td>";
while($rows = mysqli_fetch_assoc($resultDEV))/*loop2*/
{
$noteDEV = $rows['NOTE_DEVOIR'];
/*to print subject mark(note)*/
echo"<td>$noteDEV</td>";
/*i add the query of average inside the loop to be with touch by all row data mark*/
$queryAVG="select avg($noteDEV) as average_devoir from devoir where MODULE_DEVOIR = '$moduleD' group by MODULE_DEVOIR ";
}
$resultAVG = mysqli_query($con,$queryAVG);
if($rows = mysqli_fetch_assoc($resultAVG))
{
if($rows = mysqli_fetch_assoc($resultAVG))
{
$avg = $rows['average_devoir'];
echo"<td>$avh</td>";
}
}
echo"</tr>";
}
echo"</table>";
}

If you are not required to use SQL to calculate the average, then doing this seems a better option.
while($rows = mysqli_fetch_assoc($result5))
{
$moduleD = $rows['MODULE_DEVOIR'];
$queryDEV = "SELECT * FROM devoir INNER JOIN eleve " .
"ON devoir.CIN_ELEVE = eleve.CIN_ELEVE " .
"WHERE eleve.CIN_ELEVE = '$cinE' " .
"AND MODULE_DEVOIR = '$moduleD' " .
"ORDER BY MODULE_DEVOIR";
$resultDEV = mysqli_query($con,$queryDEV);
/*to print subject name*/
echo"<tr><td>$moduleD</td>";
// We will use this variable to store the sum
$sum = 0;
// And this is a counter to store the number of results
$count = 0;
while($rows = mysqli_fetch_assoc($resultDEV))/*loop2*/
{
$noteDEV = $rows['NOTE_DEVOIR'];
/*to print subject mark(note)*/
echo"<td>$noteDEV</td>";
// Update the sum
$sum += $noteDEV;
// Update the counter
$count ++;
}
// Calculate and display the average
$avg = $sum / $count;
echo "<td>$avh</td>" . "</tr>";
}
If you know that the number of results is always constant, and equals 5, you can get rid of the $count variable and divide by 5 directly.
You may also wish to format the output to fit your needs.

Related

how to get count(*) the right way in php

I tried to count() the data from database with php but it don't show me the total data but it show the datas.
this is how I count
$query = "SELECT
mitra.*,
user.username,
user.privilege,
user.name
FROM
mitra
INNER JOIN
user ON mitra.id_user = user.id "
$result = $connection->query($query);
if ($result->num_rows > 0) {
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = "" . $row["total_puas"] . "";
$privilege = "" . $row["privilege"] . "";
if ($privilege == 2) :
$calculate = $total / count($id);
var_dump(count($id));
endif;
endforeach;
}
===================
= id = total =
= 1 = 45.84 =
= 2 = 75.45 =
= 3 = 34.54 =
===================
when I var_dumb it it shows int(1)int(1)int(1) not int(3) that what I wanted.
actually I want to count $calculate with the data in $total that should be there is float and the amount from $total that I want to divided with count id
is there any solution that how to count the amount from $total and can be devided with count $id that should be 3?. please help
what I really trying to do from that table example is like 45.84 + 75.45 + 34.54 / 3
Sounds like you want a COUNT() with GROUP BY in your query. Doing count($id) in PHP will always yield one, as its not an array of values.
$query = "SELECT COUNT(id) as cnt, id, total_puas
FROM table
GROUP BY id";
$result = $connection->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$calculate = $row["total_puas"] / $row['cnt'];
echo $row['id']." has a count of ".$row['cnt'].", a total of ".$row['total_puas']." and calculated to ".$calculate."<br />\n";
}
}
From your updated question, the output becomes a bit more clear. Based on the output data and the result you desire, you want to calculate the sum of all total_paus, divided by the number of rows. You can do this directly in one query, like this
$query = "SELECT SUM(total_puas) / COUNT(u.id) as total
FROM mitra AS m
INNER JOIN user AS u
ON mitra.id_user = user.id";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$total = $row['total'];
echo $total;
You can try this code:
<?php
$i = 0;
$total =0.00;
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()):
if ($row["privilege"] == 2) :
$total = $total + $row["total"];
$i++;
endif;
endwhile;
echo $total."<br>";
echo $i."<br>";
echo $calculate = $total / $i;
}
?>
output
=====================================
$total = 155.83;
$i = 3;
$calculate = $total/$i;
$ans = 51.943333333333;
=====================================
You can try this code:
$query = "SELECT * FROM table"
$result = $connection->query($query);
if ($result->num_rows > 0) {
$total = 0.0;
foreach ($result as $row) :
$id = "" . $row["id"] . "";
$total = $total + $row['total'];
endforeach;
$calculate = $total / $result->num_rows;
echo $total.<br>;
echo $calclulate;
}

inline td with th using loop in PHP

So I have this tables on my database that I have to display as table in html. The problem is I do not know how I am going to inline my td with my th and add zero to the person who doesn't have allowance.
This is the image of my allowance table
.
So far this is what i have:
<?php
error_reporting(0);
include "./includes/connectdb.php";
$emp = "select * from employee";
$q = $dbhandle->query($emp);
if($q->num_rows>0){
$all = "select distinct allowance from emp_allowances order by allowance asc";
$a = $dbhandle->query($all);
if($a->num_rows>0) {
while($b = $a->fetch_assoc()){
$thallowance .= '<th>'.$b['allowance'].'</th>';
$empallowance = $b['allowance'];
}
}
while($r = $q->fetch_assoc()){
$id= $r['id'];
$name= $r['name'];
$all2 = "select * from emp_allowances order by allowance asc";
$c = $dbhandle->query($all2);
if($c->num_rows>0){
$tdallow='';
while($d = $c->fetch_assoc()){
$empid = $d['emp_id'];
$empallowance = $d['allowance'];
$amount = $d['amount'];
if($empid==$id){
$tdallow.='<td>'.$amount.'</td>';
}
}
}
$tbody .= '<tr>
<td>'.$name.'</td>
'.$tdallow.'
</tr>';
}
}
$thead = '
<thead>
<tr>
<th>Name</th>
'.$thallowance.'
</tr>
</thead>
';
?>
<table border=1>
<?php echo $thead; ?>
<tbody>
<?php echo $tbody; ?>
</tbody>
And from this code i got this result.
I changed your while loop, try to copy it and see if works.
The $tdarray sets all allowances to zero, if some of them has a greater value it is set in the employee allowances loop. This way if there is no allowance for an employee there will be zero and properly inline, because the default values (zeros) are preset.
Let me know if works.
<?php
error_reporting(0);
include "./includes/connectdb.php";
$emp = "select * from employee";
$q = $dbhandle->query($emp);
if($q->num_rows>0){
// array that will hold key value pairs for allowances
$tdarray = array();
$all = "select distinct allowance from emp_allowances order by allowance asc";
$a = $dbhandle->query($all);
if($a->num_rows>0) {
while($b = $a->fetch_assoc()){
$thallowance .= '<th>'.$b['allowance'].'</th>';
$empallowance = $b['allowance'];
// fill the array with keys (allowances) and default, zero values
$tdarray[$b['allowance']] = 0;
}
}
// Looping through employees
while($r = $q->fetch_assoc()){
$id= $r['id'];
$name= $r['name'];
$all2 = "select * from emp_allowances order by allowance asc";
$c = $dbhandle->query($all2);
if($c->num_rows>0){
$tdallow='';
// Looping through employee allowances
while($d = $c->fetch_assoc()){
$empid = $d['emp_id'];
$amount = $d['amount'];
$empallowance = $d['allowance'];
if($empid==$id){
$tdarray[$empallowance] = $amount;
}
}
}
$tbody .= '<tr>';
$tbody .= '<td>'.$name.'</td>';
foreach ($tdarray as $allowance => $amount) {
$tbody .= '<td>'.$amount.'</td>';
// reset to zero
$tdarray[$allowance] = 0;
}
$tbody .= '</tr>';
}
try adding else with your code:
if($empid==$id){
$tdallow.='<td>'.$amount.'</td>';
}else{ // add else block for print zero
$tdallow.='<td>0</td>';
}

Doing a PHP While Loop Inside A While Loop

I am trying to do a php while loop inside another php while loop but when I get to the second loop it doesn't go back to the first one and reloop again Here is the code I am using:
Database connection string is in a separate module. The first while Loop should loop twice but what I think is happening when it gets to the second database while loop that loop returns positive and it affects the first loop so I only get 1 loop from the first loop. Can someone please tell me how I could change this to avoid this problem?
These are the two loops below from a database:
while($row = $result->fetch_assoc()) {
// Show/Hide Regions:
error_reporting(-1);
ini_set('display_errors', 'On');
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
$sql = "SELECT id, region FROM tbl_region;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0; //Set count to 1
while($row = $result->fetch_assoc()) {
$counter++; //Increment counter by 1's
$rID = $row["id"];
?>
Output Region Here!
<?php
//Output companies for this region.
$sql = "SELECT
tbl_company.company_name,
tbl_company.group_number,
tbl_region.region
FROM
tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
} ?>
Change inner loop $row and $result with any other name..for example I have done $rowInner and $resultInner here.
<?php
while($row = $result->fetch_assoc()) {
if ($result->num_rows > 0) {
$counter = 0; //Set count to 1
while($row = $result->fetch_assoc()) {
$counter++; //Increment counter by 1's
$rID = $row["id"];
?>
Output Region Here!
<?php
$sql = "SELECT
tbl_company.company_name,
tbl_company.group_number,
tbl_region.region
FROM
tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC
";
$resultInner = $conn->query($sql);
if ($resultInner->num_rows > 0) {
while($rowInner = $resultInner->fetch_assoc()) { // Change $row to $rowInner
echo $rowInner["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
}
}
?>
You should use a different variable for $result like $result2 for 2 while loops. That is causing the conflict.
You overwritten the first $row/$result with the second $row/$result. Try using a different name for the second set of results.
// Show/Hide Regions:
error_reporting(-1);
ini_set('display_errors', 'On');
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
$sql = "SELECT id, region FROM tbl_region;";
$result =
$conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0; //Set count to 1
while($row = $result->fetch_assoc()) {
$counter++; //Increment counter by 1's
$rID = $row["id"];
?>
Output Region Here!
<?php
//Output companies for this region.
$sql = "SELECT
tbl_company.company_name,
tbl_company.group_number,
tbl_region.region
FROM
tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC
";
$result2 = $conn->query($sql);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
echo $row2["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
} ?>
You should use different variables for inner and outer while loops. Try the following:
<?php
// Show/Hide Regions:
error_reporting(-1);
ini_set('display_errors', 'On');
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
$sql = "SELECT id, region FROM tbl_region;";
$resultOuter = $conn->query($sql);
if ($resultOuter->num_rows > 0)
{
// output data of each row
$counter = 0; //Set count to 1
while($rowOuter = $resultOuter->fetch_assoc())
{
$counter++; //Increment counter by 1's
$rID = $rowOuter["id"];
//Output companies for this region.
$sql = "SELECT tbl_company.company_name, tbl_company.group_number, tbl_region.region
FROM tbl_region
INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
WHERE
$rID = tbl_company.region_id
ORDER BY
tbl_company.company_name ASC ";
$resultInner = $conn->query($sql);
if ($resultInner->num_rows > 0)
{
// output data of each row
while($rowInner = $resultInner->fetch_assoc())
{
echo $rowInner["company_name"]."<br>";
}
}
echo "A";
echo '</div>';
}
}
?>

Repeating SQL insert statement in loop till id has certain value?

<?php
include ("db.php");
$id2 = "SELECT MAX(id) FROM osalejad;";
$id = $conn->query($id2);
if (id<= 8){
while($id<= 7) {
$min = 1;
$max = 20;
$suvanumber = rand($min, $max);
$bar = (string) $suvanumber;
$prii= "vaba2" . $bar;
$sql="INSERT INTO osalejad (name) VALUES ('$prii')";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
else {
echo '8 osalejat on juba kirjas';
}
?>
I have a question, i want to insert data into MYSQl table, word with a random number, but problem is, it never work as it should - if i have 3 records in name column, then till, it adds 8 more records, instead of 5 records. Is something outside of scope atm?
I will use the DB in this code.
<?php
include("db.php");
$sql = "SELECT * FROM `osalejad`;";
$result = $conn->query($sql);
$var = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = mysqli_fetch_array($result)) {
$var[] = $row["name"];
}
} else {
/// echo "0 results";
}
//shuffle the array, and encode into json.
shuffle($var);
$brack=json_encode($var);
$testbrack= json_encode(array_chunk($var,2));
$final = '{';
$final .= '"teams":';
$final .= $testbrack;
$final .= ',"results":[[[[0,0],[null,null]],[[null,null],[null,null]]]]}';
//updating last tournament bracket.
$sql1 = "UPDATE lan_brackets SET json='$final' ORDER BY tid DESC LIMIT 1;";
$roundOne=$conn->query($sql1);
?>

join query not working properly

I want to select two table values so I am using join query see below, from this code I stored one session variable like $_SESSION['emp_id'], I want select query like who are in te.emp_id='".$_SESSION['emp_id']."', From this code $count will return 0 but in my database I have one row.
$q = mysql_query("SELECT *
FROM task_employee te
JOIN task t
ON te.emp_id = t.t_assign_to
WHERE t.t_status = '0'
AND t.t_delete_on != '1'
AND te.emp_id = '" . $_SESSION['emp_id'] . "'");
$data = array();
while($r = mysql_fetch_assoc($q))
{
$data[] = $r;
}
$count = sizeof($data);
if($count > 0)
{
$return = array('status'=>'success', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
else
{
$return=array('status'=>'not-found', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
I am writing like this means I can get but using join query that time I can't get values
<?php
$sql = mysql_query("SELECT *
FROM task
WHERE t_delete_on !='1'
AND t_assign_to = '$emp_id'");
for ($i = 1; $row = mysql_fetch_assoc($sql); $i++)
{
$assign_to = $row['t_assign_to'];
$mysql = mysql_query("SELECT *
FROM task_employee
WHERE emp_id = '$assign_to'");
while ($r = mysql_fetch_assoc($mysql))
{
$emp_name = $r['emp_firstname']; // here i got value
}
}
?>

Categories