I'm trying to change the order of MySQL results depending on if an if condition is met in PHP.
My code checks to see if any rows are duplicates and changes the row class if it is.
What I'm trying to achieve is if there is a duplicate then the MySQL query is ordered by Frequency and if there are no duplicates found then order it by Name.
This is what I have:
function getFrequencies() {
$conn = getConnected("websiteData");
$frequencyQuery = "
SELECT
f.Name,
f.Frequency,
f.Country,
f.Programmed,
(SELECT count(*) FROM frequencies WHERE Frequency = f.Frequency) as count
FROM frequencies f;
";
$frequencyResult = mysqli_query($conn, $frequencyQuery);
while ($frequencyRow = mysqli_fetch_assoc($frequencyResult)) {
if($frequencyRow['count'] > 1) {
$frequencyQuery = "
SELECT
f.Name,
f.Frequency,
f.Country,
f.Programmed,
(SELECT count(*) FROM frequencies WHERE Frequency = f.Frequency) as count
FROM frequencies f
ORDER BY Frequency;
";
} else {
$frequencyQuery = "
SELECT
Name,
Frequency,
Country,
Programmed
FROM frequencies
ORDER BY Name;
";
}
}
$frequencyResult = mysqli_query($conn, $frequencyQuery);
while ($frequencyRow = mysqli_fetch_assoc($frequencyResult)){
if ($frequencyRow['count'] > 1) {
echo '<tr class="warning">' .
"<td>" . $frequencyRow['Name'] . "</td>" .
"<td>" . $frequencyRow['Frequency'] . "</td>" .
"<td>" . $frequencyRow['Country'] . "</td>" .
"<td>" . $frequencyRow['Programmed'] . "</td>" .
"</tr>" . PHP_EOL;
} else {
echo "<tr>" . PHP_EOL .
"<td>" . $frequencyRow['Name'] . "</td>" .
"<td>" . $frequencyRow['Frequency'] . "</td>" .
"<td>" . $frequencyRow['Country'] . "</td>" .
"<td>" . $frequencyRow['Programmed'] . "</td>" .
"</tr>" . PHP_EOL;
}
}
}
Now I know for a fact that my table contains duplicates but currently there aren't any highlighted rows and the order is by Name.
Before I changed my code to the above stated one it was this one which did highlight my duplicate rows:
function getFrequencies() {
$conn = getConnected("websiteData");
// $frequencyQuery = "SELECT Name, Frequency, Country, Programmed, count(*) FROM frequencies GROUP BY Frequency ORDER BY Name";
$frequencyQuery = "
SELECT
f.Name,
f.Frequency,
f.Country,
f.Programmed,
( SELECT count(*) FROM frequencies WHERE Frequency = f.Frequency ) as count
FROM frequencies f
ORDER BY Frequency;
";
$frequencyResult = mysqli_query($conn, $frequencyQuery);
while ($frequencyRow = mysqli_fetch_assoc($frequencyResult)) {
if ($frequencyRow['count'] > 1) {
echo '<tr class="danger">' . PHP_EOL .
"<td>" . $frequencyRow['Name'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Frequency'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Country'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Programmed'] . "</td>" . PHP_EOL .
"</tr>" . PHP_EOL;
} else {
echo "<tr>" . PHP_EOL .
"<td>" . $frequencyRow['Name'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Frequency'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Country'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Programmed'] . "</td>" . PHP_EOL .
"</tr>" . PHP_EOL;
}
}
}
What can I do to achieve what I am trying to do? The reason I want to change the order is because when there are no duplicates it is a preference to scroll through the list alphabetically, but if there are duplicates then ordering it by Frequency puts the duplicates one row after the other making it easy to find and edit/delete.
Based on what you're trying to do I would build an Associative Array of the results and then use your logic to order them using PHP instead of MySQL's order by clause.
A method you could take (if you want to retain all duplicates) would be to build the table by sorting the array by the Name key and then saying if unique display else for each duplicate in array display which will result in all of the duplicates being displayed in succession, with the entire thing sorted by Name alphabetically, you can use asort for this.
In order to stop this from triggering side effects you could build two arrays, one from the MySQL select and one that is unique using array_unique that way when you loop through the array to display the page you can loop through the unique array and only grab the duplicate elements from the original array when rendering.
Consider the following:
<?php
$array = array();
$uniqueArray = array_unique($array);
for ( $i = 0; $i < sizeof($uniqueArray); ++$i ) {
if ( in_array($uniqueArray[$i], $array) ) {
// Item has duplicates
} else {
// item is unique
}
}
?>
If you don't want to retain duplicates you can quite simply follow the same formula but upon matching a duplicate instead of displaying them you can purge each of them from the database only retaining one then render the item from the unique array.
Related
I have this SQL query: I need some sort of conditional WHERE clause if possible to use the WHERE clause on EVERYTHING except this Row Below -> $row['value_count_deaths'].
I do not want this one to be filtered and to show the whole number before being filtered.
Is this possible within the same query? If so ... how?
IMG: I want to accumulate the death number after their name, must be outside WHERE clause
Focus of Code:
echo "<td style='text-align: center'>" . $row['pe_DataPlayers_lastname'] . " " . $row['value_count_deaths'] . "</td>";
All overall coded query statement:
echo "<h3> All Pilot Statistics (Realistic/Hardcore) ... only populate stats after last pilot death for each pilot</h3>";
if ($result = $mysqli->query("SELECT a.`pe_LogEvent_pilotname`,
COUNT(a.`pe_LogEvent_deaths`) AS value_count_deaths,
COUNT(a.`pe_LogEvent_kills_planes`) AS value_count_kills_planes,
COUNT(a.`pe_LogEvent_kills_helicopters`) AS value_count_kills_helicopters,
COUNT(a.`pe_LogEvent_kills_armor`) AS value_count_kills_armor,
b.`pe_DataPlayers_lastname`,
b.`pe_DataPlayers_updated`,
b.`pe_DataPlayers_id`,
c.`pe_LastPilotDeath_pilotname`,
c.`pe_LastPilotDeath_datetime`
FROM `pe_LogEvent` AS a
INNER JOIN `pe_DataPlayers` AS b
ON a.pe_LogEvent_pilotname = b.pe_DataPlayers_lastname
LEFT JOIN `pe_LastPilotDeath` AS c
ON b.pe_DataPlayers_lastname=c.pe_LastPilotDeath_pilotname
WHERE a.`pe_LogEvent_datetime` > c.`pe_LastPilotDeath_datetime`
GROUP BY b.`pe_DataPlayers_lastname`
ORDER BY b.`pe_DataPlayers_updated` DESC")) {
echo "<table>";
echo "<table class='table_stats'>";
echo "<tr class='table_header'><th>Pilot</th><th>Last Flight Log</th><th>A2A Kills</th><th>A2G Kills</th><th>Sorties</th><th>Landing%</th><th>Deaths</th><th>Ejections</th><th>Crashes</th><th>PVP Kills</th><th>Team Kills</th><th>Planes</th><th>Helos</th><th>Armor</th><th>Light Vehicles</th><th>UnArmored</th><th>Air Defense</th><th>Artillery</th><th>Infantry</th><th>Ships</th><th>Structures</th></tr>"; // First Code
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td style='text-align: center'>" . $row['pe_DataPlayers_lastname'] . " " . $row['value_count_deaths'] . "</td>";
echo "<td style='text-align: center'>" .
$row['value_count_deaths'] . "</td>";
echo "<td style='text-align: center'>" . $row['value_count_ejections'] . "</td>";
echo "<td style='text-align: center'>" . $row['value_count_crashes'] . "</td>";
//echo "<td style='text-align: center'>" . $row['value_sum_pvp'] . "</td>";
echo "</tr>";
}
echo "</table>";
$result->close();
}
A typical approach would be to use a subquery to create a flag.
Your code looks like MySQL, so this uses MySQL syntax conventions:
SELECT SELECT pe_LogEvent_pilotname, pe_LogEvent_friendly_fire_killer,
COUNT(*) as total,
SUM(pe_LogEvent_crashes IS NOT NULL AND flag) AS value_count_crashes,
. . .
FROM (SELECT le.*,
. . . , -- other columns you want
(le.pe_LogEvent_datetime > lpd.pe_LastPilotDeath_datetime) as flag
FROM pe_LogEvent le JOIN
pe_DataPlayers dp
ON le.pe_LogEvent_pilotname = dp.pe_DataPlayers_lastname LEFT JOIN
pe_LastPilotDeath lpd
ON dp.pe_DataPlayers_lastname = lpd.pe_LastPilotDeath_pilotname
) x
GROUP BY . . .
Explanations:
First of all im new in the database field, i got system from my boss, my boss ask me to create dashboard based on the data from database, but some data need to join other table in different database. In my case i need to fetch data at column score from table rank in 4 different database which is "virtualexam, virtualexam1, virtualexam2, virtualexam3,"
. I had try and search but i cant display the data into the table, your advice and recommendation really appreciate it.. Thank you for you kindness
Error picture
click here
Database Table Picture *Dummy data
db.virtualexam
db.virtualexam1
db.virtualexam2
db,virtualexam3
my query
<?php
$sql = "SELECT virtualexam.rank.id, virtualexam.rank.username,
virtualexam.rank.score AS score, virtualexam1.rank.score AS 'score1', virtualexam2.rank.score AS 'score2', virtualexam3.rank.score AS 'score3'
SUM(virtualexam.rank.score + virtualexam1.rank.score + virtualexam2.rank.score + virtualexam3.rank.score ) AS 'total'
FROM virtualexam.rank
JOIN virtualexam1.rank ON virtualexam.rank.username = virtualexam1.rank.username,
JOIN virtualexam2.rank ON virtualexam1.rank.username = virtualexam2.rank.username,
JOIN virtualexam3.rank ON virtualexam2.rank.username = virtualexam3.rank.username
GROUP BY id ";
$result = $conn->query($sql);
?>
display in the table
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "<td>" . $row['score1'] . "</td>";
echo "<td>" . $row['score2'] . "</td>";
echo "<td>" . $row['score3'] . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>";
}
?>
</tbody>
$sql = "SELECT virtualexam.rank.id, virtualexam.rank.username,
virtualexam.rank.score AS score, virtualexam1.rank.score AS 'score1', virtualexam2.rank.score AS 'score2', virtualexam3.rank.score AS 'score3',
SUM(virtualexam.rank.score + virtualexam1.rank.score + virtualexam2.rank.score + virtualexam3.rank.score ) AS 'total'
FROM virtualexam.rank
JOIN virtualexam1.rank ON (virtualexam.rank.username = virtualexam1.rank.username)
JOIN virtualexam2.rank ON (virtualexam2.rank.username = virtualexam1.rank.username)
JOIN virtualexam3.rank ON (virtualexam3.rank.username = virtualexam2.rank.username)
GROUP BY virtualexam.rank.username";
So i have to have a page where all of the logs from another one of our pages is echoed out.
$query = "SELECT * FROM `returnform` WHERE department_id=1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<tr class='divEnglish'> <td>" . $row['name'] . "</td>" . " " . "<td>" . $row['returned_date'] . "</td>" . " " . "<td>" . $row['lost'] . "</td>" . " " . "<td>" . $row['lossnum'] . "</td>" . " " . "<td>" . $row['putback'] . "</td>","</tr>";
};
I need all of the rows echoed out to be put in order from newest to oldest so that when people view the page the latest logs.
You need to add order by clause into your query.
$query = "SELECT * FROM `returnform` WHERE department_id=1 ORDER BY create_date DESC";
I suppose you have date, when to record was created, the column name is create_date.
I have a select on a database, like this:
$result = mysql_query("
SELECT dat_eb_registrants.id, dat_eb_registrants.first_name,
dat_eb_registrants.last_name, dat_eb_registrants.email, dat_eb_registrants.comment,
dat_eb_registrants.amount, dat_eb_registrants.published,
dat_eb_registrants.transaction_id, dat_eb_registrants.register_date,
dat_eb_field_values.field_value
FROM dat_eb_registrants LEFT JOIN dat_eb_field_values
ON dat_eb_registrants.id=dat_eb_field_values.registrant_id
WHERE dat_eb_field_values.field_id='53' AND `event_id` >= 20 AND `event_id` <= 25
ORDER BY $sort $ascdsc
");
and it gets diplayed in a html table like so:
echo "
ID
First name
Last name
Email
Comment
Value1
Value2
Value3
";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "<td>" . $row[9] . "</td>";
echo "<td>" . $row[?] . "</td>";
echo "<td>" . $row[?] . "</td>";
echo "</tr>";
echo "</table>";
}
Now, the first 4 values are being displayed correctly, just like the 5th one, but how about the 6th and the 7th one? they are not being called by MYSQL because dat_eb_field_values.field_value is only called one time, and is assigned the value WHERE dat_eb_field_values.field_id='53
How can i complete the table with the other values in the database?
Thanks in advance, Laurent
If I understand correctly, you are trying to load multiple values for each person. These values are in multiple rows in a separate table.
You'll need to use a GROUP BY clause. JOIN the registrants table with the values table just like you do now, and after the WHERE clause, GROUP BY the registrant's id. And of course, don't restrict the WHERE to a certain value's ID, because then you won't get any other values. Finally, you can use GROUP_CONCAT() to get all the value rows into a single result value, delimited by ,. You can change this to be delimited by </td><td> to make it easier to put into your table.
SELECT registrants.name, GROUP_CONCAT(values.value SEPARATOR '</td><td>')
FROM registrants
LEFT JOIN values USING (registrant_id)
WHERE ...
GROUP BY registrant_id
Voitek Zylinski answer is I think the best way to do this. but you could try a for each.
while ($row = mysql_fetch_row($result))
{
echo "<tr>";
foreach($row as $row_item)
{
echo "<td>".$row_item."</td>"
}
echo "</tr>";
}
This would work no matter how many field
Total newbie trying to learn... thanks for all the help so far!
UPDATE - updated code below - Thanks Phill
I'm now trying to get the relevant horse information from a table horses which I can join to race_form with the horse_name field. I want to then display the information for each horse in the race below the while($racecard) info. Does this make it a bit clearer?
I thought I could just do another query and then a while loop with mysql_fetch_array below the one I have already and that would display it and then move onto the next race, but that apparently doesn't work...?!
I'm wondering if you can run 2 while loops after each other inside a while loop? I am working on a horse racing formguide - I can display each race list, but underneath I want to display individual horse details on each horse in the race. Anyway if you look at this page you can see what I'm trying to do:
http://tasmanianracing.com/superform/formguide.php?meetingID=21042011LAUN&Submit=View+Form
Problem is, any time I put a second while loop after the race list, it won't show up. I'm trying to run a query to get the horse details from my horse table and then run a while for each horse in the race, but nothing shows up.
I hope this is clear enough ... my snippet of code is below - please let me know if I've missed out something important:
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $row['race_number'] . " at " . $row['start_time'] . " " . $row['class'] . " over " . $row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $row['raceID'] . "')");
while($row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $row['number'] . "</td><td>" . $row['past10'] . "</td><td>" . $row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
echo "</table>";
You'll probably need to change the names of some of the $row variables, they may interfere with each other.
For example:
while($row_races = mysql_fetch_array($totalraces)){
while($row_details = mysql_fetch_array($racedetails)){
while($row_card = mysql_fetch_array($racecard)){
I think you can get rid of one of your queries:
The first query gets the number of races by selecting a COUNT, This returns one record with the count value.
// This returns one record with the count
$total_races = "SELECT COUNT(race_number) AS totalraces
FROM race_info WHERE meetingID = ('".$safemeetingID."') ";
Next you iterate over the the same records as the rows returned for the race details are the same as the count.
// This looks to return the record(s) with the race details
$race_details = "SELECT * FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')";
I think you can just use this to get the desired results: (I agree to rename the $row variable(s) to something descriptive for each while loop)
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
NOT TESTED/PSEUDO CODE
"SELECT *
FROM horses AS h,
INNER JOIN race_info AS ri ON race_form.raceID = race_info.raceID
WHERE horse_name IN (
SELECT horse_name
FROM race_form AS srf
WHERE h.horse_name = srf.horse_name
)
AND race_form.raceID = ('" . $details_row['raceID'] . "')"
The idea is to join the two queries into one, I know this is not the correct syntax but it might give you an idea on how to go about it.
Or you can do another query while loop for the horse names
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
$horses = mysql_query("SELECT *
FROM horses
WHERE horse_name = ('" . $rc_row['horse_name'] . "')");
while($horse_row = mysql_fetch_array($horses))
{
// echo horse details here
}
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
I theory you could and in practice you can, but a while in a while in a for in a while seems a little bit over the top...
I'm sure we can help you make it more efficient if you explain what it is you're trying to do.