Wordpress - Get All Rows In HTML Table - php

I have a custom wordpress table and am trying to get all rows in the db separated by year. My code now:
echo "<table width='100%'>";
for ($year = date("Y"); $year >= 2017; --$year) {
echo ("<tr><th>$year</th></tr>");
echo ("<tr><th>Champions</th>");
echo ("<th>Score</th>");
echo ("<th>Date</th></tr>");
global $wpdb;
$clubmatch = $wpdb->get_results("SELECT * FROM wp_club ORDER BY gamedate DESC");
foreach($clubmatch as $row){
echo "<tr><td>" . $row->names . "</td>";
echo "<td>" . $row->score . "</td>";
echo "<td>" . $row->gamedate . "</td></tr>";
}
echo ("<tr><td style='padding: 20px;'></td></tr>");
}
echo '</table>';
This gives me the following on screen:
2018
Champions Score Date
Sam Jones - Peggy Jones 81.43 2018-03-01
Joseph Parks - Carmen Parks 70.85 2017-12-17
2017
Champions Score Date
Sam Jones - Peggy Jones 81.43 2018-03-01
Joseph Parks - Carmen Parks 70.85 2017-12-17
How do I get it to show like this? Each row under the proper year?
2018
Champions Score Date
Sam Jones - Peggy Jones 81.43 2018-03-01
2017
Champions Score Date
Joseph Parks - Carmen Parks 70.85 2017-12-17
Thanks in advance!

Change the SQL query, so that it filters the result by the year of the field gamedate. So use this: (the code is indented for clarity)
$clubmatch = $wpdb->get_results(
"SELECT * FROM wp_club " .
"WHERE YEAR(gamedate) = '$year' " .
"ORDER BY gamedate DESC"
);
..instead of:
$clubmatch = $wpdb->get_results("SELECT * FROM wp_club ORDER BY gamedate DESC");

Related

mysqli query to fetch row values without loop

I am newbie and need help to resolve my issue.
extract row values without loop.
Table:
----------------
YEAR | SALES
----------------
2011 | 45
2012 | 34
2013 | 23
2014 | 10
2015 | 48
----------------
PHP code:
$sql = "SELECT YEAR FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "YEAR: " . $row["YEAR"]. "<br>";
}
} else {
echo "0 results";
}
looking for solution to output the year value without loop , something similar below
while loop prints all row values , but would like to extract individual year value from query and assign it to a variable
$year1 = $row["YEAR"]
$year2 = $row["YEAR"]
$year3 = $row["YEAR"]
with your current code
$i=1;
while($row = $result->fetch_assoc()) {
${'year'.$i}= $row["YEAR"];
$i++;
//echo "YEAR: " . $row["YEAR"]. "<br>";
}
now you can access $year1; $year2 and so on

Break and continue in a while loop

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

Echo variable once

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>";
}

How to add up votes in a table and display it on screen

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>';

sum in query / subquery

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.

Categories