how to get count(*) the right way in php - 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;
}

Related

Average of horizontals data mysql 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.

Display a new div after every number of records fetch from database in MySQL

I want to create a div for ads on a project I'm working on. I want the div to show after 8 records is fetch from the database.
My select statement:
$query = mysql_query("SELECT * FROM posts WHERE `username` = '$followe' OR `user_id` = ' $get_id' ORDER BY date_added DESC LIMIT 15 ");
$newsCount = mysql_num_rows($query); // Count the output amount
if ($newsCount > 0) {
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$user_post_id = $row["user_id"];
$username = $row["username"];
$text = $row["texts"];
$profile_pix = $row["profile_pix"];
}
}
You need to add a counter for your while loop and echo the HTML string when the counter is divisible by 8:
<?php
$query = mysql_query("SELECT * FROM posts WHERE `username` = '$followe' OR `user_id` = ' $get_id' ORDER BY date_added DESC LIMIT 15 ");
$newsCount = mysql_num_rows($query); // Count the output amount
if ($newsCount > 0) {
$rowcount=1;
$divhtml = "<div></div>";
while ($row = mysql_fetch_assoc($query)){
if ($rowcount % 8 == 0) {
echo $divhtml;
}
$rowcount++;
$id = $row["id"];
$user_post_id = $row["user_id"];
$username = $row["username"];
$text = $row["texts"];
$profile_pix = $row["profile_pix"];
}
}
?>
You should change the content of variable $divhtml, with your own ad HTML.
Use an accumulator pattern such as this.
$i = 0
while($row = mysql_fetch_assoc($query)){
$i++;
if(i == 8) {
// DO WHATEVER
}
$id = $row["id"];
$user_post_id = $row["user_id"];
$username = $row["username"];
$text = $row["texts"];
$profile_pix = $row["profile_pix"];
}

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
}
}
?>

Check if FK order is numbered correctly

I have some absences, and each absence has an FK to an employee, which I wanna display in a generated HTML table. However, if I delete an employee the order changes from 0, 1, 2 to 1, 2 (for example if the second employee got deleted).
This messed up my code, because I need the FK to check where I have to insert the leave (in which <tr>). Here I count the employees:
$result = mysql_query("select count(1) FROM employee");
$row = mysql_fetch_array($result);
$count_user = $row[0];
Later in my code I make a query in a loop. The loop runs as many times as there are users. And heres the problem: if an employee gets deleted it will not reach the other one ($i goes 0 and then 1 if there are 2 users, but if one is deleted the FK is 3, so it would need to go one further).
to
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = $i");
while ($row = mysql_fetch_assoc($result)) {
$array_absences[] = $row;
}
Has anyone an Idea that is not based on the FK order?
Also this topic needs a better title so feel free to edit it.
<html>
<head>
<title>Absence System</title>
</head>
<body>
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("absence_system", $con);
$result = mysql_query("select count(1) FROM employee");
$row = mysql_fetch_array($result);
$count_user = $row[0];
$result = mysql_query("select count(1) FROM absences");
$row = mysql_fetch_array($result);
$count_absences = $row[0];
$result = mysql_query("select name, surename, employee_ID FROM employee");
while ($row = mysql_fetch_assoc($result)) {
$array_user[] = $row;
}
for($i = 0; $i < $count_user; $i++){
echo '<table = border = 1px>';
echo '</tr>';
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = $i");
while ($row = mysql_fetch_assoc($result)) {
$array_absences[] = $row;
}
$count = count($array_absences);
echo $count;
print_r($array_absences);
for($j = 0; $j < 32; $j++){
$true = 0;
if($j == 0){
echo '<td>';
echo $array_user[$i]['name'], " ", $array_user[$i]['surename'] ;
echo '</td>';
}
for($k = 0; $k < $count; $k++)
{
$array_absences[$k]['start'] = substr($array_absences[$k]['start'], -2);
$array_absences[$k]['end'] = substr($array_absences[$k]['end'], -2);
$array_absences[$k]['start'] = ereg_replace("^0", "", $array_absences[$k]['start']);
$array_absences[$k]['end'] = ereg_replace("^0", "", $array_absences[$k]['end']);
if($j == $array_absences[$k]['start'] && $array_absences[$k]['employee_FK'] == $i){
$true = 1;
echo '<td>';
echo $array_absences[$k]['type_FK'];
echo '</td>';
}
}
if($j != 0 && $true == 0){
echo '<td>';
echo "$j";
echo '</td>';
}
}
echo '</tr>';
echo '</table>';
}
?>
</body>
</html>
If employee_ID corresponds to employee_FK, then you should not iterate over $count_user, but rather over $array_user - then your select would looke like this:
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = {$array_user[$i]['employee_ID']}");
while $i will still represent sequence number, because
$count_user == count($array_user)

PHP paging, viewing a certain page first

This is my script for the paging on my site when the user clicks on a league.
The league is then echoed to the screen, and if the league is over 3 rows then it splits it up in to several pages.
What I am doing after is depending on where the user is in the league (the SQL query is using ORDER BY the total points column in the table), e.g if the user is on page one of the league table then for it to display that page first, but if the user is on page 3 of the league table then for that page to displayed first.
Does anyone know a way in order for me to achieve this?
//Recently updated from answer
$sql="SELECT members.username, members.total_points FROM members, members_leagues WHERE members.username = members_leagues.username AND
members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC";
$result=mysql_query($sql);
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row($result)){
if ($row[username] == $_SESSION[username]) {
$team_position = $i;
$found = true;
}
$i++;
}
$rowsPerPage = 3;
$pageNum = ceil($i/$rowsPerPage);
//end of recently updated
if(isset($_GET['page']))
$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$counter = $offset + 1;
$query = " SELECT members.username, members.teamname, members.total_points, FROM members, members_leagues WHERE members.username = members_leagues.username AND members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC " . " LIMIT $offset, $rowsPerPage";
$result = mysql_query($query) or die('Error, query failed');
echo "<h3 style=\"color:red;\">$chosenleague</h3>";
echo "<table>";
echo "<tr><th>Position</th>";
echo "<th>Team</th>";
echo "<th>Points/Overall</th>";
echo "<th>Points/Last Race</th>";
echo "<th>Team Setup</th></tr>";
while($row = mysql_fetch_array($result))
{
if($row[username] == $_SESSION[username])
echo "<tr style=\"color:red;\"><td>";
else
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $row[teamname];
echo "</td><td>";
echo $row[total_points];
echo "</td><td>";
echo "</td><td>";
echo "</td></tr>";
$counter++;
}
echo "</table>";
$query = "SELECT COUNT(members.username) AS numrows FROM members, members_leagues WHERE members.username = members_leagues.username
AND members_leagues.sub_league = '$chosenleague'";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxPage = ceil($numrows/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
$nav = '';
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " << Prev ";
$first = " First ";
}
else
{
$prev = '';
$first = '';
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " Next >> ";
$last = " Last ";
}
else
{
$next = '';
$last = '';
}
echo "<div id=\"pagenum\">Page $pageNum of $maxPage ". $first . $last . $prev . $next ."</div>";
You can do it via mysql or php:
With PHP:
Found the position of the requested record in the array, then calculate the page you have to extract and execute the corresponding query. Something like.
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row) {
if ($row['team'] == 'team_your_searching_for') {
$team_position = $i;
$found = true;
}
$i++;
}
//calculate $top and $bottom
...
$sql = "SELECT * FROM members LIMIT $top, $bottom;";
...
With MySQL:
You can create a query that generates an autoincrement value and another that selects from the other's result. I mean
-- get the the selected member's position
SELECT team, pos FROM (SELECT team, points, #position = #position + 1 AS pos FROM members ORDER BY points) WHERE team = #the_team_your_searching_for;
-- get the nr of members
SELECT COUNT(*) FROM members;
...
-- calculate the page you wanna extract (#top, #bottom), and extract it
SELECT * FROM members LIMIT #top, #bottom;

Categories