Problem
Basically I have got a game where 2 teams are competing with each other. With first while loop I get those team names and information. In the second loop I am fetching username/members who are participating in those teams and then run a query to fetch their records.
The final while loop I have used to Some up the teams calculation, i.e. if Team A have 2 players named as Joe and Mike and Team B have 3 players named as John,Jack and Dave So for Team A Joe did ran 5 km and Mike ran 7 km which brings up to a total of 12 km for team A. Likewise for team B John ran 11km, Jack did 2 km and Dave did 1km which makes a total of 14km for team B. But because of this loop is shows Team A = 12km and Team B = 26km. It will be great if anyone can guide me through to where I might be going wrong.
Code
$t_name = "Joe Running8 Vs Mike Running2";
$sql_team = 'SELECT * FROM teams WHERE t_name="'.$t_name.'" AND game_type = "Activity"';
$result_team = mysql_query($sql_team) or die(mysql_error());
$totalNoUsers = '';
$activityTotal = '';
$avgPP = '';
//Table structure for displaying the results
echo '<table border="1" align="center" width="100%">';
echo '<tr>';
echo '<th>Team Name</th>';
echo '<th>Total no Activity</th>';
echo '<th>Total Users</th>';
echo '<th>Avg per User</th>';
echo '<th>Avg %</th>';
echo '</tr>';
while($row_team = mysql_fetch_array($result_team)){
$sql_SelUsers = 'SELECT * FROM teams where t_name="'.$row_team['team'].'"';
echo $sql_SelUsers."<hr>";
$result_SelUsers = mysql_query($sql_SelUsers) or die(mysql_error());
$totalNoUsers = mysql_num_rows($result_SelUsers);
while($row_SU = mysql_fetch_array($result_SelUsers)){
//$accepted_on = "30/01/2013";
$userA = explode("/","27/01/2014");
$accepted_on = mktime(0,0,0, $userA[1],$userA[0],$userA[2]);
$date_time_compare = date('D, j M Y H:i:s', $accepted_on);
$sql = 'SELECT * FROM data_feeds where username="'.$row_SU['username'].'" AND gadget_data_type= "Activity" and gadget_name = "'.$row_SU['gadget_type'].'" and gadget_sub_data_type = "'.$row_SU['game_parameter'].'" and STR_TO_DATE( date_time, "%a, %e %b %Y %H:%i:%s" ) >= STR_TO_DATE( "'.$date_time_compare.'", "%a, %e %b %Y %H:%i:%s" ) ORDER BY df_id DESC';
$result_df = mysql_query($sql) or die(mysql_error());
echo $row_SU['username']."<br />";
/****** Here is the problem ********/
while($row_df = mysql_fetch_array($result_df)){
$activityTotal += $row_df['gadget_data_type_value'];
echo "<br /><strong>".$activityTotal."</strong><br />";
}
}//end while query data_feeds
echo "TnP-> ".$totalNoUsers;
$activityTotal = $activityTotal/1000;
$avgPP = ($activityTotal/$totalNoUsers);
echo '<tr>';
echo '<td>'.$row_team['challToTeam'].'</td>';
echo '<td>'.number_format($activityTotal, 2, '.', ',').'</td>';
echo '<td>'.$totalNoUsers.'</td>';
echo '<td>'.number_format($avgPP, 2, '.', ',').'</td>';
echo '<td>'.$totalNoUsers.'</td>';
echo '</tr>';
}//end while query Teams
echo '</table>';
You need to reset $activityTotal before your loop.
After the first loop its value is 12 km, and
then you add 14 km to it, which becomes 26km instead of 14 km .
Correction:
$activeTotal = 0 // RESET TO ZERO
while($row_df = mysql_fetch_array($result_df)){
$activityTotal += $row_df['gadget_data_type_value'];
echo "<br /><strong>".$activityTotal."</strong><br />";
}
$activityTotal set to empty or 0 before next team total start
//use
$activityTotal = 0; //init to 0 before loop
Related
I have a database of pupils from which I want to group each pupil according to their form class. At the moment I can only do this by looping within each group. Is there a better way to do this. What I want the results to look like is this:
Year 1
Form Class 1
Pupil Y, Pupil , Pupil K
Form Class 2
Pupil G, Pupil A, Pupil Z
Year 2
Form Class 3
Pupil A, Pupil U, Pupil Q
Form Class 4
Pupil V, Pupil R, Pupil M
Year 3
Form Class 5
Pupil G, Pupil S, Pupil D
Form Class 6
Pupil W, Pupil P, Pupil C
The database looks like this:
+----+------+----------+-------+
|Year|Class |First Name|Surname|
+----+------+----------+-------+
|1 |Class3|Jenny |James |
|1 |Class1|John |Bruces |
|1 |Class1|Dirk |Diggler|
|1 |Class2|Michael |Johnson|
+----+------+----------+-------+
The coding I have tried so far is:
<?php
$pupil_details = $_SESSION['pupdetails'];
$selectclass = $connect->query("SELECT DISTINCT Year FROM `$pupil_details` ORDER BY class DESC");
while ($rows = $selectclass->fetch_array()) {
echo $rows["Year"];
$yrlvl = $rows['Year'];
?><br/><?php
$selectpup = $connect->query("SELECT DISTINCT class from `$pupil_details` where Year ='$yrlvl'");
while ($rowsd = $selectpup->fetch_array()) {
$yrlvlclass = $rowsd['class'];
echo $yrlvlclass;
?><br/><?php
$wholeSchool = mysqli_query($connect, "SELECT * from $pupil_details where class ='$yrlvlclass' ORDER BY surname asc");
while ($row = mysqli_fetch_array($wholeSchool)) {
echo $row["firstname"];
echo $row["surname"];
}
}
}
?>
Can anybody suggest a better way to do this?
I tested this and it worked:
$selectPupil = $connect->query("select * from `pupils` order by Year, Class, Surname");
$neededForFirstValue = 0;
while ($row = $selectPupil->fetch_array()) {
//set initial values for year
if($neededForFirstValue == 0) {
$previousYear = $row['Year']; //takes the value to compare
echo "Year " . $previousYear . "<br />"; //display first year
$neededForFirstValue = 1; //to never go into that if again
}
$currentYear = $row['Year']; //takes current year value
if($currentYear == $previousYear) { //check if year has changed, if not, keep going
//set initial values for class
if($neededForFirstValue == 1) {
$previousClass = $row['Class']; //takes the value to compare
echo "Class: " . $previousClass . "<br />"; //display first year
$neededForFirstValue = 2; //to never go into any if again
}
$currentClass = $row['Class'];
if($currentClass == $previousClass) {
echo $row['First Name'] . " " . $row['Surname'] . "<br />"; //display a pupil
} else {
echo "Class: " . $currentClass . "<br />"; //display current year
echo $row['First Name'] . " " . $row['Surname'] . "<br />"; //display first user in each class
}
} else {
echo "Year " . $currentYear . "<br />"; //display current year
}
$previousClass = $row['Class']; //remember the year to compare
$previousYear = $row['Year']; //remember the year to compare
}
You could do all with a single query simply ordering by year, class and surname
select *
from your_table
order by Year, class, surname
but don't use var inside your php code .. you are at risk for sql injection .. and in your case the use of object (table name) in var in alos not allowed in SQL
So What I want to do is to echo 1 for the first row that is returned and two for the 2nd one and so one, Please I just don't know how to phrase this, I don't want to just count rows from mysql table, I want to give each row a number automatically and echo that number.
Please forgive my deprecated code.
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
while($row = mysql_fetch_array($log)){
echo row['name'];
}
Lets assume that the above returns some names. so I want this.
1 : John
2 : Nancy
3 : Dave
I don't want to write those number.
Please take into account ORDER by rate DESC since I'm using that to descent the number by the biggest number of rate.
You could do:
$count = 1;
while($row = mysql_fetch_array($log)){
echo $count . ' ' . row['name'];
$count++;
}
Or:
echo '<ol>';
while($row = mysql_fetch_array($log)){
echo '<li>' . row['name'] . '</li>';
}
echo '</ol>';
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
$c = 0
while($row = mysql_fetch_array($log)){
echo row['name'];
$c = $c + 1;
}
echo "Raw Count = ".$c
How can i display variable only once in the table.
<?php
$sql = mysql_query("SELECT * FROM babydata");
while ($row = mysql_fetch_array($sql)) {
for ($i = 1; $i <= 72; $i++) {
if ($i == $weeknumber) {
echo "<tr><td width='40'>Week $i</td>";
echo "<td width='500' >" . count($row[$menucompare]) . "</td></tr>";
}
}
}
?>
this code display like this:
--------------
week4 | 1
-------------
week4 | 1
-------------
But i want to display weeknumber only once and count($row[$menucompare]) will be counted 2 in week 4 . not 1 and 1 .
Like this:
--------------
week4 | 2
---------------
Seems like you want to output the amount of tuples in babydata for a certain week. You can just filter out any tuples which dont belohnt to the $weeknumber in your query.
// TODO: Assert, that $weeknumber is an integer, to not be prune to SQL injection.
$weeknumber = (int)(($currentdate - $birthday) / (7 * 24 * 60 * 60)) + 1;
// Select the amount of tuples in babydata for the desired $weeknumber.
$result = mysql_query("SELECT count(*) FROM babydata ".
"WHERE week = $weeknumber");
// There is only one tuple with one column that contains the amount as number.
$row = mysql_fetch_row($result);
// Output the week and the amount of data.
echo "<tr><td width='40'>Week $weeknumber</td>" ;
echo "<td width='500' >".$row[0]."</td></tr>";
No need for loops.
To output all weeks and their respective amount of data:
// Select the amount of tuples in babydata for all weeks.
$result = mysql_query("SELECT week, count(*) FROM babydata ".
"GROUP BY week");
// For all weeks:
while ($row = mysql_fetch_row($result))
{
// Output the week and the amount of data.
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}
This assumes that you have a column week in your table babydata that contains just a number. This outputs only weeks, that have at least one tuple.
You can do that directly in the SQL. Warning: I didn't actually tested this.
SELECT week, count(week) FROM babydata GROUP BY week;
This will directly return a result like
--------------
week4 | 2
week5 | 3
--------------
Just replace week with the actual name of your week field, and adapt the PHP to handle the new result structure. Something along these lines:
$sql= mysql_query("SELECT * FROM babydata");
while($row = mysql_fetch_array($sql))
{
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}
i have a php code which selects and shows data from my 'elections' table. i have another table called 'votes' which contains all the votes by users. how do i select the two tables and show the party that has had the most votes? so if labour had 5 votes for example and lib dems had 3 votes, how would i show on screen that 'labour has won this election with __ votes? my php is as follows:
<?php
$id = $_GET['election'];
$result = mysql_query("SELECT election_id, name_of_election, date, month, year FROM elections WHERE election_id = '$id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo '<hr><h3>There Aren\'t Any Elections Setup Yet</h3><hr> ';
} else {
echo '<hr><h3>Vote Count</h3><hr>';
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name_of_election']. "</td>";
echo "<br/><br/><td>" . $info['date']. ' '. $info['month']. ' ' . $info['year']. "</td>";
echo "<br/><br/><td>" . '<hr>' . "</td>";
}
}
echo "</tr>";
echo "</table>";
?>
my database table consists of the following fields:
(dont ask about the date fields)
elections: election_id, name_of_election, date, month, year, party1, party2, party3, status
votes: vote_id, election_id, ni, party
any ideas?
This will give you the party and count for selected election in descending order of count:
$result = mysql_query(
sprintf("
SELECT votes.party, COUNT(votes.vote_id)
FROM votes
WHERE election_id = %d
GROUP BY election_id, votes.party
ORDER BY COUNT(votes.vote_id) DESC",
mysql_real_escape_string($id)
)
);
Edit: To display the first row (which will be the party with the most votes):
list($party, $votes) = mysql_fetch_row($result);
echo '<p>'.$party.' won with '.$votes.'</p>';
Table has the following info:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-10| 10 |42.50| 4.25 |
2009-03-03| 21 |23.50| 2.30 |
2009-03-10| 21 |32.50| 3.25 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-10| 18 |44.50| 4.45 |
I want it to sort into separate tables depending on date as follows:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-03| 21 |23.50| 2.30 |
date |vendor|sales|percent|
--------------------------
2009-03-10| 10 |42.50| 4.25 |
2009-03-10| 18 |44.50| 4.45 |
2009-03-10| 21 |32.50| 3.25 |
I can get this done but I cannot get it to give me the totals for each separate table like:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-03| 21 |23.50| 2.30 |
Total Sales for 2009-03-03 = $90.50
Total percent for 2009-03-03 = $8.90
date |vendor|sales|percent|
--------------------------
2009-03-10| 10 |42.50| 4.25 |
2009-03-10| 18 |44.50| 4.45 |
2009-03-10| 21 |32.50| 3.25 |
Total Sales for 2009-03-03 = $119.50
Total percent for 2009-03-03 = $11.95
I can get the totals for all but not for individual tables.
Here is my code:
<?php
$con = mysql_connect("localhost", $dbUser, $dbPassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("beans", $con);
$result = mysql_query("SELECT * FROM Deposits WHERE market = '4' ORDER BY eventdate, vendor ASC") or die(mysql_error());
$dateChk = 0;
while($row = mysql_fetch_array($result))
{
$date = $row["eventdate"];
$liclass = $row["vendor"];
$url = $row["trxid"];
$amountdep = $row["amount"];
$depcheck = $row["checkno"];
$deposit_Total = $deposit_Total + $amountdep;
$deposit_3Total = $deposit_3Total + $depcheck;
$deposit_3 = $amountdep / 100;
$dep_percent = $deposit_3 * 3;
$depper_Total = $depper_Total + $dep_percent;
$week = date("W", db_date_to_timestamp($date));
$year = date("Y", db_date_to_timestamp($date));
If($dateChk != $week)
{
echo "<table class=\"adverts\" width=\%100\" cellpadding=\"4\">\n";
echo "<tr><th>Date</th><th>Vendor</th><th>Total Sales</th><th>3% Due</th><th>Week</th></tr>\n";
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
$dateChk = $week;
}
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_3Total . "</b></p>\n";
?>
(EDIT: sorry when I posted I saw that you need it in the query!)
$dateChk = 0;
$firstRow = 1;
while($row = mysql_fetch_array($result))
{
$date = $row["eventdate"];
$liclass = $row["vendor"];
$url = $row["trxid"];
$amountdep = $row["amount"];
$depcheck = $row["checkno"];
$deposit_Total = $deposit_Total + $amountdep;
$deposit_3Total = $deposit_3Total + $depcheck;
$deposit_3 = $amountdep / 100;
$dep_percent = $deposit_3 * 3;
$depper_Total = $depper_Total + $dep_percent;
$week = date("W", db_date_to_timestamp($date));
$year = date("Y", db_date_to_timestamp($date));
If($dateChk != $week)
{
if($firstRow == 0)
{
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_week_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_week_3Total . "</b></p>\n";
$deposit_week_Total = 0;
$deposit_week_3Total = 0;
}else
{
$firstRow = 0;
}
echo "<table class=\"adverts\" width=\%100\" cellpadding=\"4\">\n";
echo "<tr><th>Date</th><th>Vendor</th><th>Total Sales</th><th>3% Due</th><th>Week</th></tr>\n";
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
$dateChk = $week;
$deposit_week_Total = $deposit_week_Total + $amountdep;
$deposit_week_3Total = $deposit_week_3Total + $depcheck;
}
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_3Total . "</b></p>\n";
?>
SQL
"SELECT date, SUM(sales) FROM Deposits WHERE market = '4' GROUP BY date"
Istead of sum(sales) you have to use your own calculations. I suggest to put them into a model.
Would this help?
http://www.plus2net.com/sql_tutorial/sql_sum.php
SELECT SUM (sales) FROM `table_name` WHERE `date` = '$date_you_want'
From my below comment:
SELECT SUM (sales) FROM `table_name` WHERE `date` <= '$start_date_of_week' AND `date` >= '$end_date_of_week'
So basically WHERE date is less than and greater than the two dates that describe the start and stop of the week you want...
Or... I think you could also add the days to the value in the mysql
SELECT SUM (sales) FROM table_name WHERE date LIKE '$yyyy-mm-dd %' ...DATE_ADD code for adding days.. or INTERVAL.
You can get those sums straight by using GROUP BY WITH ROLLUP.