how do you join two tables - php

i have a mysql query which is trying to join to tables to show the data from two tables onto one table on the webpage?
<?php
include 'library/connect.php';
$result = mysql_query("SELECT * FROM meetings INNER JOIN rooms USING ('room', 'date', 'time' ) ");
echo "<table border='1'><tr><th>Title</th><th>Chairman</th><th>Secretary</th><th>Terms of Reference</th><th>Named membership</th><th>Occurences</th><th>Room</th><th>Date</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['title']. "</td>";
echo "<td>" . $row['chairman']. "</td>";
echo "<td>" . $row['secretary']. "</td>";
echo "<td>" . $row['termsOfReference']. "</td>";
echo "<td>" . $row['occurences']. "</td>";
echo "<td>" . $row['room']. "</td>";
echo "<td>" . $row['date']. "</td>";
echo "<td>" . $row['time']. "</td>";
echo "</tr>";
}
echo "</table>";
include 'library/closedb.php';
?>
do i need both table id somewhere?

I'd doubt that date and time are columns in your rooms table, so they shouldn't be part of the JOIN condition. Try:
SELECT *
FROM meetings m
INNER JOIN rooms r
ON m.room = r.room

By "Using" keyword it will check both tables by column names. It will check inner join on Ist condition then it will get left join on next columns if result not found.
it's bad practice to use "Using" keyword.
Simplify joins by USING.
By
-Multiple columns
-Single column

Related

Select Statement Conditional WHERE Clause - How do you add a variable not affected by WHERE clause in same query

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 . . .

Trying to join different table from different database in the localhost, Used MYSQL

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

Adding a rank to my mySQL output data [duplicate]

This question already has answers here:
ROW_NUMBER() in MySQL
(26 answers)
Closed 6 years ago.
The code below is returning a table with data from mysql, but what I'm missing in the output is a generated column with a rank based on a column's data (wilks in this example). I've looked for examples and answers to similar questions, but I can't get it to work.
In short: I need an extra column next to the ID column where a rank beginning from 1 is displayed, based on the data from the Wilks column.
Thank you so much!
<?php
$con=mysqli_connect("localhost", "user", "password", "dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `Mannen` ORDER BY `Wilks` DESC");
echo "<table border='1'>
<tr>
<th>#</th>
<th>Naam</th>
<th>Lichaamsgewicht</th>
<th>Vereniging</th>
<th>Squat</th>
<th>Bench</th>
<th>Deadlift</th>
<th>Totaal</th>
<th>Wilks</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Naam'] . "</td>";
echo "<td>" . $row['Lichaamsgewicht'] . "</td>";
echo "<td>" . $row['Vereniging'] . "</td>";
echo "<td>" . $row['Squat'] . "</td>";
echo "<td>" . $row['Bench'] . "</td>";
echo "<td>" . $row['Deadlift'] . "</td>";
echo "<td>" . $row['Totaal'] . "</td>";
echo "<td>" . $row['Wilks'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
First, if you just want an enumerated value, you can get that using PHP.
But, it is easy enough in MySQL, using variables:
SELECT m.*, (#rn := #rn + 1) as rank
FROM Mannen m CROSS JOIN
(SELECT #rn := 0) params
ORDER BY Lichaamsgewicht DESC;
Technically, this implements the related function of row_number() rather than rank(). Your question is unclear on what you mean by "rank".

Very strange SQL error where data is not being pulled correctly

I have two pages that are very similar, but do slightly different things. However, both place data into a table called playerRegSeason.
Here is the SQL code I use on one page:
$sql2="INSERT INTO playerRegSeason
(playerID, year, teamID, gp, minutes, pts, oreb, dreb, reb,
asts, stl, blk, turnover, pf, fga, fgm, fta, ftm, tpa, tpm)
SELECT playerID, $year, '$teamID', $gp, $minutes, $pts, $oreb,
$dreb, $reb, $asts, $stl, $blk, $turnover, $pf, $fga, $fgm,
$fta, $ftm, $tpa, $tpm FROM players WHERE firstname='".$firstname."'
AND lastname='".$lastname."' AND firstseason='".$firstseason."'";
And here's the code for the other page:
$sql2="INSERT INTO playerRegSeason
(playerID, year, teamID, gp, minutes, pts, oreb, dreb, reb,
asts, stl, blk, turnover, pf, fga, fgm, fta, ftm, tpa, tpm)
VALUES ($playerID, $year, '$teamID', $gp, $minutes, $pts, $oreb,
$dreb, $reb, $asts, $stl, $blk, $turnover, $pf, $fga, $fgm,
$fta, $ftm, $tpa, $tpm)";
On both pages, when I look at the database, the data has been added and is in the proper format.
Now, is my problem. I have another page that displays the contents of the table. Here is the code that is not working:
$quer1 = "SELECT * FROM players p
INNER JOIN playerRegSeason pr ON p.playerID = pr.playerID
INNER JOIN teams t ON pr.teamID = t.teamID
WHERE p.firstname='$firstname' AND p.lastname='$lastname'";
$result1 = mysqli_query($con, $quer1);
while($row = mysqli_fetch_array($result1)) {
echo "<tr>";
echo "<td>" . $row['year'] . "</td>";
echo "<td>" . $row['location']." ". $row['name'] . "</td>";
echo "<td>" . $row['leag'] . "</td>";
echo "<td>" . $row['gp'] . "</td>";
echo "<td>" . $row['minutes'] . "</td>";
echo "<td>" . $row['pts'] . "</td>";
echo "<td>" . $row['oreb'] . "</td>";
echo "<td>" . $row['dreb'] . "</td>";
echo "<td>" . $row['reb'] . "</td>";
echo "<td>" . $row['asts'] . "</td>";
echo "<td>" . $row['stl'] . "</td>";
echo "<td>" . $row['blk'] . "</td>";
echo "<td>" . $row['turnover'] . "</td>";
echo "<td>" . $row['pf'] . "</td>";
echo "<td>" . $row['fga'] . "</td>";
echo "<td>" . $row['fgm'] . "</td>";
echo "<td>" . $row['fta'] . "</td>";
echo "<td>" . $row['ftm'] . "</td>";
echo "</tr>";
echo "</table>";
}
The weird thing is that any data entered from the first sql will not show up, but any data that was entered through the second sql statement will. Even though both entries are listed right next to each other in the db with the same playerID primary key.
You are doing two inner joins, you already confirmed one of them when you said that both entries have the same player ID, but do they also both have the same teamID?
If the first entry doesn't have a teamID that exists in the teams table, it won't be coming in through your query.
A quick way to check this is to change the 'INNER JOIN' on the teams table with an LEFT JOIN, if this gets you more records then your data has some teamID values that don't exist in the teams table.
In the second set of sql inserts you're always going to do an insert (assuming no errors with variables, etc.)
In the first set of sql, you're doing a select statement to perform the insert, specifically look at your where clause - if that clause eliminates all returned results, then no records will be inserted. If you run the statement:
SELECT *
-- input your expected values in place of the variables
FROM players WHERE firstname= ''
AND lastname='' AND firstseason='';
you'll likely see that nothing is being returned from this query, therefore nothing would be inserted in the first query.
Based on your comment it sounds like the issue (since it wasn't due to the first sql statement) would likely be due to the inner joins:
try your query as such:
SELECT * FROM players p
--INNER JOIN playerRegSeason pr ON p.playerID = pr.playerID
--INNER JOIN teams t ON pr.teamID = t.teamID
WHERE p.firstname='$firstname' AND p.lastname='$lastname
See if you're getting your expected value. If you are, uncomment the inner join on playerRegSeason, if still getting your expected row, uncomment the join on teams. The likely cause is that at least one of the tables you're joining on does not contain the record you're expecting, and therefore is not being returned by the query. (or as David suggested, change your inner joins to left joins for testing purposes)

Continue MYSQL output in PHP

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

Categories