MySQL database selecting athlete data requires position - php

I am selecting data from a database and displaying it on the page.
One useful value which is not saved in the database is the $position.
It is useful to show the position of each athlete, here as shown I just display an increasing $i value.
The code shown below ORDERS BY run points. The problem is when sorting the list say by something else such as ORDER BY athlete ASC the position allocated to each athlete doesn't move with the athlete.
$selectproduct = mysqli_query($link, "SELECT `athlete`,`reference`,SUM(`Run Points`) AS 'Run Points',COUNT(`eventID`) AS 'num_runs',`Volunteer Points`,`location`,`Gender pos` FROM `Events` WHERE `Gender`='$Gender' AND `location`='$location' GROUP BY `reference` ORDER BY `Run Points` DESC");
while ($rowGetDetails = mysqli_fetch_array($selectproduct)){
$reference=$rowGetDetails['reference'];
$athlete=$rowGetDetails['athlete'];
$points=$rowGetDetails['Run Points'];
$num_runs=$rowGetDetails['num_runs'];
$position=$i;
echo '<tr>';
echo'<td>';
echo $athlete;
echo '</td>';
echo'<td>';
echo $num_runs;
echo '</td>';
echo'<td>';
echo $points;
echo '</td>';
echo '</tr>';
$i=$i+1;
}
When sorting by something else such as athlete ASC in the $selectproduct it still gives $postition as number 1 for the first athlete in the list with a name beginning with A when that is not the athlete with the most points.
There are other options for $selectproduct such as sorting by athlete ASC as below:
$selectproduct = mysqli_query($link, "SELECT `athlete`,`reference`,SUM(`Run Points`) AS 'Run Points',COUNT(`eventID`) AS 'num_runs',`Volunteer Points`,`location`,`Gender pos` FROM `Events` WHERE `Gender`='$Gender' AND `location`='$location' GROUP BY `barcode` ORDER BY `athlete` ASC"

Just assign $i value outside the loop;
$selectproduct = mysqli_query($link, "SELECT `athlete`,`reference`,SUM(`Run Points`) AS 'Run Points',COUNT(`eventID`) AS 'num_runs',`Volunteer Points`,`location`,`Gender pos` FROM `Events_08052017_withdate` WHERE `Gender`='$Gender' AND `location`='$location' GROUP BY `reference` ORDER BY `Run Points` DESC");
$i = 1;
while ($rowGetDetails = mysqli_fetch_array($selectproduct)){
$reference=$rowGetDetails['reference'];
$athlete=$rowGetDetails['athlete'];
$points=$rowGetDetails['Run Points'];
$num_runs=$rowGetDetails['num_runs'];
$position=$i;
echo '<tr>';
echo'<td>';
echo $athlete;
echo '</a>';
echo '</td>';
echo'<td>';
echo $num_runs;
echo '</td>';
echo'<td>';
echo $points;
echo '</td>';
echo '</tr>';
$i=$i+1;
}
try query something like this may be its works for you
SET #rank=0;
SELECT #rank := #rank + 1 AS ranking, t.avg, t.name
FROM(SELECT avg(students_signatures.score) as avg, students.name as name
FROM alumnos_materia
JOIN (SELECT #rownum := 0) r
left JOIN students ON students.id=students_signatures.id_student
GROUP BY students.name order by avg DESC) t

Related

Getting data from my join table

I have a join table which takes the id from my respondents table respondant_id and the id from my teams table table_id.
The output is fine when I SELECT from that table so I get back the respondants ID married up with the teams ID.
I am wanting to show the respondents name from respondant_data and the team name from teams by using the values output from the join table.
I have attempted this here but I keep getting 0 results.
$sql = "
SELECT
respondant_data.respondant_id, teams.team_id
FROM
respondant_data
INNER JOIN
teams
ON
respondant_data.respondant_id = teams.team_id
WHERE
respondant_teams.team_id= 5";
$result = $conn->query($sql);
$i = 1;
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $i++ . ' ';
echo 'user_id: ' . $row["respondant_id"] . ', ';
echo 'team_id: ' . $row["team_id"];
echo '<br>';
}
} else{
echo 'no results';
}
So I want my output to be like 'John Smith', 'Central Team'
Try this query.
SELECT
resp_data.respondant_id, teams.team_id
FROM
respondant_data resp_data,
teams,
respondant_teams resp_teams
WHERE
resp_data.respondant_id = teams.team_id
and resp_teams.team_id = teams.team_id
and resp_teams.team_id = 5

Conditional WHERE clause in SELECT using if statements and php variable

I'm trying to build a table that is conditionally organized based off user input. I need my WHERE and GROUP BY clauses to change based off user input values (from radio selects sent to php through ajax - these tested successfully), stored in php variables. I tried to run a series of if statements to change the WHERE and GROUP BY clauses based on the values of the ajax data variables and then concat then into my SELECT statement. I try the same method for building the column headers and the table itself. When I test the current code, the table headers display (the first column is empty because of the variable) but the columns aren't built. I don't receive any errors when I inspect the page and my ajax variables display the appropriate values.
The problem is definately with the IF statements but I'm not sure how to fix that.
Note: the SQL statements works perfectly when I manually enter a WHERE or GROUP BY clause using the same values I'm trying to store in variables.
MY CODE:
AJAX Response:
//Get Table Type.
if (isset($_POST['revenueTblType'])) {
$revenueTblType = $_POST['revenueTblType'];
print_r($revenueTblType);
};
//Get Report Type
if (isset($_POST['revenueWO'])) {
$revenueWO = $_POST['revenueWO'];
print_r($revenueWO);
};
//Get date include value.
if (isset($_POST['revenueWODate'])) {
$revenueWODate = $_POST['revenueWODate'];
print_r($revenueWODate);
};
//Get date range.
$revenuefromajax=$_POST['revenuefrom'];
$revenuetoajax=$_POST['revenueto'];
$revenuefromstring = strtotime($revenuefromajax);
$revenuetostring = strtotime($revenuetoajax);
$revenuefrom=date("Y-m-d", $revenuefromstring);
$revenueto=date("Y-m-d", $revenuetostring);
//Get selected Status Values.
if (isset($_POST['revenue_checkboxes'])) {
$revenue_check = $_POST['revenue_checkboxes'];
};
IF STATEMENTS and TABLE BUILD:
///////////// Select Data and Display it in a table. //////////////
//$groupbyclause = "";
if ($revenueTblType=='Customer') {
$groupbyclause="x.company ASC";
$columnheader='Customer';
$columnname='company';
}
else if ($revenueTblType=='Revenue Category') {
$groupbyclause="x.revenue ASC";
$columnheader='Revenue Category';
$columnname='revenue';
}
//$whereclause = "";
if (($revenueWO=='Completed Workorders') and ($revenueWODate=='All Workorders')) {
$whereclause="x.stagestatus = 'Complete'";
}
else if (($revenueWO=='Completed Workorders') and ($revenueWODate=='Workorder Date Range')) {
$whereclause ="x.stagestatus = 'Complete' AND x.shippeddate BETWEEN '".$revenuefrom."' AND '".$revenueto."'";
}
else if ($revenueWO=='Workorder Status') {
$whereclause ="x.stagestatus IN (". implode(',', array_map(function($item) {return '"' . $item . '"'; }, $revenue_check)) .")";
}
echo "<BR>";
echo "<BR>";
//SELECT statement pulls ALL COMPLETED history info by CUSTOMER.
$sql="SELECT x.company, x.revenue, x.stagestatus, x.shippeddate, FORMAT(SUM(x.totprice), 2) as totalprice, FORMAT(SUM(x.sgtotquantity), 2) as totqty, FORMAT(SUM(x.sgtotalsqft), 2) as sgtotsqft, FORMAT(SUM(x.totprice)/SUM(x.sgtotalsqft), 2) as avgsqftrevenue, FORMAT(SUM(x.totprice)/SUM(x.sgtotquantity), 2) as avgunitrevenue FROM (SELECT t1.company, t1.revenue, t1.stagestatus, t1.shippeddate, t1.id, TRIM(LEADING '$' FROM t1.totalprice) AS totprice, t2.invoiceid, SUM(t2.quantity) AS sgtotquantity, SUM(t2.width * t2.height * t2.quantity ) /144 AS sgtotalsqft, (t1.totalprice/(SUM(t2.width * t2.height * t2.quantity ) /144)) as avgsqftrev, (t1.totalprice) / SUM(t2.quantity)) AS avgunitrev
FROM invoices AS t1 INNER JOIN lineitems AS t2 ON t1.id = t2.invoiceid
WHERE (t2.invoiceid = t1.id)
GROUP BY t1.id) x
WHERE '".$whereclause."'
GROUP BY ".$groupbyclause.""; //this line edited per comment suggestions.//
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<thead>
<tr>
<th>".$columnheader."</th>
<th>Total Revenue</th>
<th>Total SQ FT</th>
<th>AVG Revenue Per SQ FT</th>
<th>Total Number of Units</th>
<th>AVG Revenue Per Unit</th>
</tr>
</head>";
if ($result = $conn->query($sql)) {
// fetch associative array
while ($row = $result->fetch_assoc()) {
echo "<tbody>";
echo "<tr>";
echo "<td>" . $row[$columnname] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sgtotsqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['totqty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
echo "</tbody>";
}//End table while.
echo "</table>";
echo "<BR>";
}//End table if.
///////////////////////////////////////////////////////////////////////////////
//Free the result variable.
$result->free();
//Close the Database connection.
$conn->close();
All suggestions are welcome. Thank you!
You have too many ' characters in query. Currently all of your WHERE statement is quoted as well as GROUP BY statement.
Change this:
WHERE '".$whereclause."'
GROUP BY '".$groupbyclause."'"
To this:
WHERE ".$whereclause."
GROUP BY ".$groupbyclause
Be caution with last line:
//SELECT statement pulls ALL COMPLETED history info by CUSTOMER.
$sql="SELECT x.company, x.revenue, x.stagestatus, x.shippeddate, FORMAT(SUM(x.totprice), 2) as totalprice, FORMAT(SUM(x.sgtotquantity), 2) as totqty, FORMAT(SUM(x.sgtotalsqft), 2) as sgtotsqft, FORMAT(SUM(x.totprice)/SUM(x.sgtotalsqft), 2) as avgsqftrevenue, FORMAT(SUM(x.totprice)/SUM(x.sgtotquantity), 2) as avgunitrevenue FROM (SELECT t1.company, t1.revenue, t1.stagestatus, t1.shippeddate, t1.id, TRIM(LEADING '$' FROM t1.totalprice) AS totprice, t2.invoiceid, SUM(t2.quantity) AS sgtotquantity, SUM(t2.width * t2.height * t2.quantity ) /144 AS sgtotalsqft, (t1.totalprice/(SUM(t2.width * t2.height * t2.quantity ) /144)) as avgsqftrev, (t1.totalprice) / SUM(t2.quantity)) AS avgunitrev
FROM invoices AS t1 INNER JOIN lineitems AS t2 ON t1.id = t2.invoiceid
WHERE (t2.invoiceid = t1.id)
GROUP BY t1.id) x
WHERE ".$whereclause."
GROUP BY ".$groupbyclause."";

Grabbing info from two different tables, assistance

I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}

taking two array and looping it with mysql query to fetch result

<?php
//db connection goes here
$arr=array('12:30:00','01:30:01','02:30:01','03:30:01','04:30:01','05:30:01','06:30:01','07:30:01');
$arr1=array('01:30:00','02:30:00','03:30:00','04:30:00','05:30:00','06:30:00','07:30:00','08:30:00');
$cnt=count($arr);
for($i=0;$i<$cnt;$i++){
$sql="SELECT count(*) FROM report WHERE DATE_FORMAT(dt,'%H:%m:%i') BETWEEN $arr[$i] AND $arr1[$i]";
}
//fetching in while and echo
this is my script that i am trying which will generate report counting number of user and number of application from two different table report and report1.
the report will be like
Time count Logged In user Count-Apps
12:30:00-01:30:00
01:30:01-02:30:00
02:30:01 -03:30:00
03:30:01-04:30:00
04:30:01-05:30:00
05:30:01-06:30:00
06:30:01-07:30:00
07:30:01-08:30:00
08:30:01-09:30:00
report table for counting number of user
user datetimeuser(datetime)
a 12:30:00
b 01:30:00
c 01:30:01
d 02:30:00
report1 table for counting number of apps
user datetimeuser(datetime)
a 12:30:00
b 01:30:00
c 01:30:01
d 02:30:00
previously i have done a script which does the work but its slowing the server as my script will be placed in cron job firing in 1 hour interval and fetching the result
previous.php
$time_ranges = array(
array('12:30:00','01:30:00'),
array('01:30:01', '02:30:00'),
array('02:30:01', '03:30:00'),
array('03:30:01', '04:30:00'),
array('04:30:01', '05:30:00'),
array('05:30:01', '06:30:00'),
array('06:30:01', '07:30:00'),
array('07:30:01', '08:30:00'),
array('08:30:01', '09:30:00'),
);
$sql="SELECT sub0.TimeRange, sub0.number, COUNT(*) AS countapps
FROM
(
SELECT
CASE
";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN STR_TO_DATE(CONCAT(CURDATE(), ' ', '$r[0]'), '%Y-%m-%d %H:%i:%s') ";
}
$sql .= "
ELSE NULL
END AS StartRange,
CASE ";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN STR_TO_DATE(CONCAT(CURDATE(), ' ', '$r[1]'), '%Y-%m-%d %H:%i:%s') ";
}
$sql .= "
ELSE NULL
END AS EndRange,
CASE ";
foreach ($time_ranges as $r) {
$sql .= "
WHEN DATE_FORMAT(dt,'%H:%i:%s') BETWEEN '$r[0]' and '$r[1]'
THEN '$r[0]-$r[1]' ";
}
$sql .= "
ELSE NULL
END AS TimeRange,
COUNT(*) as number
FROM report
WHERE DATE_FORMAT(dt,'%Y:%m:%d')=DATE(CURDATE())
GROUP BY StartRange, EndRange, TimeRange
HAVING TimeRange IS NOT NULL
) sub0
LEFT OUTER JOIN report1
ON report1.dt BETWEEN sub0.StartRange AND sub0.EndRange
GROUP BY sub0.TimeRange, sub0.number";
$query=mysql_query($sql);
echo'<html>
<head>
<title>Count User Info TimeWise</title>
</head>
<h1>Count User</h1>
<table border="3" cellspacing="2">
<tr>
<th>range</th>
<th>count</th>
<th>Apps Count</th>';
while($row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>" . $row['TimeRange'] . "</td>";
echo "<td>" . $row['number'] . "</td>";
echo "<td>" . $row['countapps'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</html>";
?>
i want to make the mysql query shorter and more precise by taking only two array and looping it.but could not really make it.please help.how can i do this taking two array and then counting(array) and for loop it and count statement in mysql
$arr=array('12:30:00','01:30:01','02:30:01','03:30:01','04:30:01','05:30:01','06:30:01','07:30:01');
$arr1=array('01:30:00','02:30:00','03:30:00','04:30:00','05:30:00','06:30:00','07:30:00','08:30:00');
$cnt=count($arr);
for($i=0;$i<$cnt;$i++){
$sql="SELECT count(*) AS test FROM report WHERE DATE_FORMAT(dt,'%H:%m:%i') BETWEEN $arr[$i] AND $arr1[$i]";
Possibly dynamically build up a select to return the times and then join that against you report table:-
$numbers = array();
foreach($arr AS $key=>$value)
{
$numbers[] = "SELECT '".$arr[$key]."' AS StartRange, '".$arr1[$key]."' AS EndRange ";
}
$dates_select = "(".implode(" UNION ",$numbers).") sub0";
$sql="SELECT sub0.StartRange, sub0.EndRange, count(report.dt)
FROM $dates_select
LEFT OUTER JOIN report
ON DATE_FORMAT(report.dt,'%H:%m:%i') BETWEEN sub0.StartRange AND sub0.EndRange
GROUP BY sub0.StartRange, sub0.EndRange";

Output distinct values in SQL column with PHP

I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
use this
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks

Categories