I'm trying to create a fixture list for a football competition currently, and i have been stuck with trying to display something like "team1name V team2name".The tables that i am trying to pull the data from are:
Team
teamID
teamname
Fixtures
hometeam
awayteam
The sql query I have written up is:
$sql = "SELECT homeTeam, awayTeam, roundID, teamID, teamName, logo, groundName, abbreviatedName, matchDate, matchTime, venue
FROM fixtures
INNER JOIN team ON fixtures.homeTeam = team.teamID
INNER JOIN ground ON ground.groundID = team.groundID";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error());
and the PHP code which i have been using to display this data is:
<?php
while ($row = mysqli_fetch_array($results))
{
?>
<tr>
<td><?php echo $row ["teamName"]?></td>
<td> V </td>
<td><?php echo $row ["teamName"]></td>
</tr>
<?php
}
mysqli_close($conn);
?>
I understand i am calling teamname twice and hence why i am getting the same name displayed, but i am unsure as to how to get my code to differentiate the two IDs and names. Any help would be greatly appreciated
This is just a SQL problem. You need to join team twice, once for home team and once for away team.
SELECT homeTeamID, awayTeamID, homeTeam.teamID homeTeamID,
awayTeam.teamID awayTeamID, homeTeam.teamName homeTeamName,
awayTeam.teamName awayTeamName
FROM fixtures
INNER JOIN team homeTeam ON fixtures.homeTeam = homeTeam.teamID
INNER JOIN team awayTeam ON fixtures.awayTeam = awayTeam.teamID
INNER JOIN ground ON ground.groundID = team.groundID
By naming the selects, you can use the separately in your PHP code.
<?php echo $row['homeTeamName']; ?> v <?php echo $row['awayTeamName']; ?>
Related
I'm working on a system, and this module is supposed to echo the contents of the database.
It worked perfectly until I added some JOIN statements to it.
I've checked and tested the SQL code, and it works perfectly. What's not working is that part where I echo the content of the JOINed table.
My code looks like this:
$query = "SELECT reg_students.*, courses.*
FROM reg_students
JOIN courses ON reg_students.course_id = courses.course_id
WHERE reg_students.user_id = '".$user_id."'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_array($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo $row["course_name"];
echo $row["course_id"];
The course_name and course_id neither echo nor give any error messages.
UPDATE: I actually need to increase the query complexity by JOINing more tables and changing the selected columns. I need to JOIN these tables:
tutors which has columns: tutor_id, t_fname, t_othernames, email, phone number
faculty which has columns: faculty_id, faculty_name, faculty_code
courses which has columns: course_id, course_code, course_name, tutor_id, faculty_id
I want to JOIN these tables to the reg_students table in my original query so that I can filter by $user_id and I want to display: course_name, t_fname, t_othernames, email, faculty_name
I can't imagine that the user_info table is of any benefit to JOIN in, so I'm removing it as a reasonable guess. I am also assuming that your desired columns are all coming from the courses table, so I am nominating the table name with the column names in the SELECT.
For reader clarity, I like to use INNER JOIN instead of JOIN. (they are the same beast)
Casting $user_id as an integer is just a best practices that I am throwing in, just in case that variable is being fed by user-supplied/untrusted input.
You count the number of rows in the result set with mysqli_num_rows().
If you only want to access the result set data using the associative keys, generate a result set with mysqli_fetch_assoc().
When writing a query with JOINs it is often helpful to declare aliases for each table. This largely reduces code bloat and reader-strain.
Untested Code:
$query = "SELECT c.course_name, t.t_fname, t.t_othernames, t.email, f.faculty_name
FROM reg_students r
INNER JOIN courses c ON r.course_id = c.course_id
INNER JOIN faculty f ON c.faculty_id = f.faculty_id
INNER JOIN tutors t ON c.tutor_id = t.tutor_id
WHERE r.user_id = " . (int)$user_id;
if (!$result = mysqli_query($conn, $query)) {
echo "Syntax Error";
} elseif (!mysqli_num_rows($result)) {
echo "No Qualifying Rows";
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row["course_name"]}<br>";
echo "{$row["t_fname"]}<br>";
echo "{$row["t_othernames"]}<br>";
echo "{$row["email"]}<br>";
echo "{$row["faculty_name"]}<br><br>";
}
}
I have a problem with this MySQL Statment. So basicly i have a table called games and i want to
display this table on my website. Table games has Foregin Keys like developer_id,
publisher_id, categorie_id, platform1_id, platform2_id, platform3_id, platform4_id, platform5_id.
I have 5 of platform because in Table platforms i have 5 records (PC, PS4, XB1, SWITCH, MOBILE). (If you guys know any better and easier solution to these platforms pls tell me.)
So now my output on my website works but for example instead of showing developer name it shows
it's ID. I know i have to INNER JOIN them and i probbably can INNER JOIN all foregin keys but the
platform one. Because i dont know how to INNER JOIN if you have more then one FK from one table.
If you need more info tell me. I will also include picture of my DB and my PHP code where i SELECT from table games.
$query = "SELECT * FROM games WHERE id = $id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>'.$row['developer_id'].'</td>';
echo '<td>'.$row['publisher_id'].'</td>';
echo '<td>'.$row['categorie_id'].'</td>';
echo '<td>'.$row['platform1_id'].'</td>';
echo '<td>'.$row['platform2_id'].'</td>';
echo '<td>'.$row['platform3_id'].'</td>';
echo '<td>'.$row['platform4_id'].'</td>';
echo '<td>'.$row['platform5_id'].'</td>';
echo '<td>'.$row['game_name'].'</td>';
echo '<td>'.$row['relese_date'].'</td>';
$intro = $row['introduction'];
$desc = $row['description'];
echo '<td>'.$row['rating'].'</td>';
echo '</tr>';
}
Picture of my DataBase
SELECT games.game_name, games.relese_date, games.introduction, games.rating, games.description, dev.name as developer, pub.name as publisher, (SELECT * FROM platforms WHERE platforms.id in (games.platform1_id,games.platform2_id,games.platform3_id,games.platform4_id,games.platform5_id)) as plats
FROM games
INNER JOIN developers AS dev ON dev.id = games.developer_id
INNER JOIN publishers AS pub ON pub.id = games.publisher_id
WHERE games.id = $id
Keep in mind that the platforms will be listed as a collection under the property plats, and each of those items will be an object of properties as.
E.X.
return object=>
developer_id
publisher_id
categorie_id
plats => [
platform1_id=>name,
platform2_id=>name,
platform3_id=>name,
platform4_id=>name,
platform5_id=>name
]
game_name
relese_date
introduction
description
rating
I need help at getting data from MySQL Database. Right now I have a query that gives me:
Tournament ID
Tournament Name
Tournament Entry fee
Tournament Start and End date
For tournaments I am registered in. Now I want, for each tournament I am registered in, to count how many users are in that tournament, my points in that tournament, etc.
That info is in table called 'ladder'
ladder.id
ladder.points
ladder.userFK
ladder.tournamentFK
Database: http://prntscr.com/99fju1
PHP CODE for displaying tournaments I am registered in:
<?php
include('config.php');
$sql = "SELECT distinct tournaments.idtournament, tournaments.name, tournaments.entryfee, tournaments.start, tournaments.end
from tournaments join ladder
on tournaments.idtournament= ladder.tournamentFK and ladder.userFK=".$_SESSION['userid']."
group by tournaments.idtournament";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$tournament="<li class='registered' data-id=".$row['idtournament']." data-entryfee=".$row['entryfee']." data-prize=".$tournamentPrize."><span class='name'>".$row['name']."</span><span class='entry-fee'>Entry fee: ".$row['entryfee']."€</span><span class='prize-pool'>Prize pool: €</span><span class='date-end'>".$row['start']."-".$row['end']."</span><span class='btns'><button>Standings</button></span></li>";
echo $tournament;
}
}
$conn->close();
?>
Usually you can combine JOIN, COUNT() and GROUP BY in your query.
Some examples:
MySQL joins and COUNT(*) from another table
This would be the query I think.Change column and table name if its not correct. Not tested but I am sure this will give you some idea to make required query
select count(ladder.tournamentId)as userCount,tournaments.name
from
ladder left join tournaments
on ladder.tournamentId = tournaments.id
where ladder.tournamentId in
(
select tournaments.id from
tournaments left join ladder
on ladder.tournamentId = tournaments.id
where ladder.userId='yourId'
) and ladder.userId <> 'yourId'
group by ladder.tournamentId
I just need a simple queries actually,
Here are my tables:
Information -> id_info, year, information_name, person_name, country_id, state_id, city_id
Country -> id, country_id, country_name
State -> id, state_id, country_id, state_name
City -> id, city_id, state_id, city_name
I have runs some queries, for example's:
SELECT *
FROM information, country, state, city
WHERE information.country_id =country.country_id
AND information.state_id = state.state_id
AND information.city_id = city.city_id
GROUP BY information.id_info;
My Simple Scripts:
echo '<td>'.$data['country_name'].'</td>
echo '<td>'.$data['state_name'].'</td>
echo '<td>'.$data['city_name'].'</td>
$data-> Is my while script with $query=mysql_query...
from the queries above only displaying two (2) data's from my database, but in the database it has five (5) data's.
Then I've trying to delete the Group statement, but the data kept looped and displaying almost 8000 data's, but I only got 5 data on tables.
I've tried everything, left join, right join, inner join....
I need help, I know it's quite simple, but how can I just display all the data normally.
Thanks.
Here My Full Scripts for displaying the data:
<table cellpadding="5" cellspacing="0" border="1">
<tr bgcolor="#CCCCCC">
<th>No.</th>
<th>Year</th>
<th>Information Name</th>
<th>Person Name</th>
<th>Country</th>
<th>State</th>
<th>City</th>
<th>Act</th>
</tr>
<?php
include('connect.php');
$query = mysql_query("SELECT *
FROM information
INNER JOIN country ON information.country_id =country.country_id
INNER JOIN state ON information.state_id = state.state_id
INNER JOIN city ON information.city_id = city.city_id
GROUP BY information.country_id, information.state_id, information.city_id") or die(mysql_error());
if(mysql_num_rows($query) == 0){
echo '<tr><td colspan="6">No data!</td></tr>';
}else{
$no = 1;
while($data = mysql_fetch_assoc($query)){
echo '<tr>';
echo '<td>'.$no.'</td>';
echo '<td>'.$data['year'].'</td>';
echo '<td>'.$data['information_name'].'</td>';
echo '<td>'.$data['person_name'].'</td>';
echo '<td>'.$data['country_name'].'</td>';
echo '<td>'.$data['state_name'].'</td>';
echo '<td>'.$data['city_name'].'</td>';
echo '<td>Detail / Edit / Delete</td>';
echo '</tr>';
$no++;
}
}
?>
You can use INNER JOIN assuming that index key is properly used:
SELECT country.country_name,
state.state_name,
city.city_name
FROM information
INNER JOIN country ON information.country_id = country.country_id
INNER JOIN state ON information.state_id = state.state_id
INNER JOIN city ON information.city_id = city.city_id
Try changing your GROUP BY and use INNER JOIN :
SELECT *
FROM information
INNER JOIN country ON information.country_id =country.country_id
INNER JOIN state ON information.state_id = state.state_id
INNER JOIN city ON information.city_id = city.city_id
GROUP BY information.country_id, information.state_id, information.city_id
It worked now, *sigh the problem is the table in information, I have to empty the table first.
It quite a lot happened to me, the records was the problem source's, I've been through this a lot. Thank you guys for the help, now it's work perfectly fine.
The two answer above worked perfectly, Thank you.
I want to display the employee's leaves which is same department with me. I only want the employee which same department with me but the output show all of the employee in database
Here is my database
table leave:{Leave_ID(PK), Data_Apply, Leave_Type, Status, Emp_ID(FK)}
table employee: {Emp_ID(PK), Emp_Name, Dept_ID(FK)}
table department: {Dept_ID(PK), Dept_Name, Dept_Desc}
As a example I'm head of department of Marketing and I want to see employee's leave detail who under me and in a same department. I tried to use function in_array to display but fail.
Here is my code
<?php
//$test = mysql_query("select * from employee");
//if(in_array($search["Dept_ID"], array($test)))
$result = mysql_query("select * from `leave`");
if ($result == FALSE)
{
die(mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $row["Leave_ID"];?></td>
<td><?php echo $row["Emp_ID"];?></td>
<td><?php echo $row["Date_Apply"];?></td>
<td><?php echo $row["Leave_Type"];?></td>
<td><?php echo $row["Status"];?></td>
<td>Profile</td>
</tr>
<?php
}
?>
Is there is any function or anything as a suggestion to used. I'm a newbie in programming and sorry for my bad english
$department_id = 4;
$result = mysql_query(' select l.*
from leave as l
join employee as e
on l.emp_id = e.emp_id
where e.dept_id = '.mysql_real_escape_string($department_id));
$department_name = 'this one';
$result = mysql_query(" select l.*
from leave as l
join employee as e
on l.emp_id = e.emp_id
join department as e
on d.dept_id = e.dept_id
where d.dept_name like '%".mysql_real_escape_string($department_name))."%'");
edit
After reading the first comment down there, I think you're saying that you essentially have an employee_id and you want to filter the query by that employee's department. So... here's some code to do that:
http://sqlfiddle.com/#!2/41bf7/1/0
There are two queries there... they're about the same so I would just choose which ever is easier for you to understand. You would add them to the PHP like this (using the first query from the sql fiddle):
$logged_in_employee_id = 1;
$result = mysql_query('select e.emp_id, e.emp_name,
l.date_apply, l.leave_type, l.status,
d.dept_name, d.dept_desc
from `leave` as l
join employee as e
on l.emp_id = e.emp_id
join department as d
on d.dept_id = e.dept_id
where d.dept_id in (
select dd.dept_id
from employee as ee
join department as dd
on dd.dept_id = ee.dept_id
where ee.emp_id = '.mysql_real_escape_string($logged_in_employee_id)).' )');
I'm not sure where you're getting the employee_id or the department_id but make sure you sanitize and validate anything you put into a query like this. I am using mysql_real_escape_string which helps but that query will still break if someone hijacks your POST data (or something) and uses a string instead of an integer value. There are some great posts on StackOverflow about how to do this; just search for sanitizing input, sql injection with PHP, and how to do prepared statements or use PDO.
Try to change your query (at the moment it takes all the records in "leave" table).
Assuming that you know the code of your department, you can use something similar (not tested):
SELECT leave.*, employee.Emp_Name, department.Dept_Name, department.Dept_Desc
FROM leave, employee, department
WHERE leave.Emp_ID=employee.Emp_ID
AND department.Dept_ID=employee.Dept_ID
AND department.Dept_ID="<your department ID>"