I'm trying to build my 1st relationship database and it looks like this so far:
Relationships Table
Partners Table
Location Table
I want to echo all the row info including the related location names on my page, how would I get the following to echo?
ID: 2 Name: Salisbury Removals Locations: Salisbury
ID: 4 Name: Inbetween Removals Locations: Salisbury, Southampton
ID: 5 Name: Southampton Removals Locations: Southampton
=====SOLVED!=====
$sql = "SELECT partner_id, partner_name, email_address, active FROM partners WHERE active ='yes' ORDER BY partner_id ASC";
$connect->query($sql);
if ($partners = $connect->query($sql)) {
foreach ($partners as $partner) {
echo '<li><ul>';
echo '<li>' . $partner['partner_id'] . '</li>';
echo '<li>' . $partner['partner_name'] . '</li>';
echo '<li>' . $partner['email_address'] . '</li>';
echo '<li>' . $partner['active'] . '</li>';
// START GET LOCATIONS FROM RELATED TABLE
echo '<ul>';
$sql2 = "SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from partners_locations r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id AND r.partner_id =" . $partner['partner_id'] . "";
$connect->query($sql2);
if ($locations = $connect->query($sql2)) {
foreach ($locations as $location) {
echo '<li>' . $location['Locations'] . '</li>';
}
} else {
echo "Error: No Locations<br>";
}
echo '</ul>';
// END GET LOCATIONS FROM RELATED TABLE
echo '</ul></li>';
}
} else {
echo "Error: No Active Partners<br>";
}
The best thing you could do is make a new table to contain the partner_id and location_id.
tbl_relationships_new
Pros for this approach :-
1).When you need to remove a location from a partner, you wouldn't need to edit the column locations. You could simply delete an entry from this new table.
2). When you need to add more data in the locations field, you could simply just insert into the new table, which is rather easy than having to update partners.locations.
Now, you could use easy left joins to get the required data.
SQL query for my table solution.
SELECT t.*,p.*,l.* FROM tbl_relationships_new t, partners p, locations l LEFT JOIN
partners
ON
t.partner_id = p.partner_id
LEFT JOIN
locations
ON
l.location_id = t.location_id
WHERE
t.partner_id = 2
UPDATE
Here are the queries based on your table structure.
1). ID: 2 Name: Salisbury Removals Locations: Salisbury
SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from relationships r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id AND r.partner_id = 2
2). When there are 2 locations.
SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from relationships r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id AND r.partner_id = 5
UPDATE
Solution without explicitly mentioning an ID.
SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from relationships r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id
<?php
$dbconn = mysqli_connect(DBSERVER, DBUSER, DBPWD, DBNAME);
$sql = "SELECT partner_id, partner_name, locations FROM Partners";
$result = mysqli_query($dbconn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: ".$row['partner_id']." Name: ".$row['partner_name']." Locations: ";
$locs = explode(",",$row['locations']);
$first = true;
foreach ($locs as $loc) {
$sql2 = "SELECT location_name FROM Locations WHERE location_id = '".$loc."'";
$result2 = mysqli_query($dbconn, $sql2);
$row2 = mysqli_fetch_assoc($result2);
$separator = ($first?"":", ");
$first = false;
echo $separator.$row2['location_name'];
}
echo "<br/>";
}
?>
First your table Table: Partners entry should be like this.
partener_id | partner_name | email_address | active | location_id
2 Test Partner ....... yes 1
5 Good Removals ....... yes 1
5 Good Removals ....... yes 2
4 Special Removals ....... yes 2
So, you could make join with Table: Locations.
After that execute below sql query.
$sql = "select * from partners Left join locations on locations.location_id=partners.location_id";
For better understanding of query execution and data display. follow below link.
http://www.w3schools.com/php/php_mysql_select.asp
Your "locations" field in the Partners table is wrong, you must create another table to handle relations between Partners and Locations, called Locations_Partners par example. This table must have 2 fields, location_id and partner_id. This way, you can relate many partners with many locations. Then, you code should look like this:
<?php
$servername = "www.server.com";
$username = "username";
$password = "password";
$dbname = "your database name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT partner_id, partner_name, location_name FROM Partners
INNER JOIN Locations_Partners ON Partners.partner_id = Locations_Partners.Partner_id
INNER JOIN Locations ON Locations_Partners.Location_id = Locations.location_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["partner_name"]. " " . $row["location_name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related
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
I am new to PHP and I just cannot figure out my code. I am using MySQL and PHP.
table: person
PK: personID
Other fields: lastName, firstName, hireDate, imgName
table: validMajors
PK: majorAbbrev
Other Fields: majorDesc
(Junction) table: personMajors
personID, majorAbbrev
When I run my code (using NATURAL JOIN) it will display the image, last&first name, and hire date. Which is great! But I need it to display their majors as well (I would like the majorAbbrev to be displayed). It also does not display people who are in the person table but are not in the personMajors table, which is an issue because we have staff members in the person table (who do not have a major since they are not a student)
Here is my code:
<table align="center">
<?php
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
if ( mysqli_connect_errno() ) {
die( mysqli_connect_error() );
}
$sql = "SELECT * FROM person NATURAL JOIN personMajors ORDER BY lastName";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
$columns=4;
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if($i % $columns ==0){
echo "<tr>";
}
echo "<td class='staffImage badgeText frameImage displayInLine'>" . "<img src='images/staff/".$row['imgName'].".jpg'>". "<br>".
"<strong>" . $row['firstName'] . "</strong>" ." ".
"<strong>" . $row['lastName'] . "</strong>" . "<br>" .
"Hire Date: ".$row['hireDate'] ."</td>";
"Major: " .$row['majorAbbrev'] ."</td>"; //Does not display
if($i % $columns == ($columns - 1)){
echo "</tr>";
}
$i++;
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</table>
Any ideas/solution will be greatly appreciated!
Because you are not concatenating your php properly. You ended (;) your echo after displaying the $row["lastName"].
You can try these to join the three tables:
SELECT * FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Or you can define what columns to call in your query:
SELECT person.personID,
person.lastName,
person.firstName,
person.hireDate,
person.imgName,
validMajors.majorAbbrev,
validMajors.majorDesc
FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Then you can call the results with the way you are calling it right now (cleaner version):
echo '<td class="staffImage badgeText frameImage displayInLine">
<img src="images/staff/'.$row["imgName"].'.jpg"><br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>
Hire Date: '.$row["hireDate"].'
Major: '.$row["majorAbbrev"].'
</td>';
(Second try): Is the person to major relationship one to one or one to many?
OK, this SELECT Statement should work:
SELECT person.*, validMajors.* FROM person AS p, validMajors AS vm, personMajors AS pm WHERE p.personID = pm.personID AND pm.majorAbbrev = vm.majorAbbrev
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>";
}
I have three tables:
I want to display 'Event Details' which shows attending employee details (listo f employee ids from the 'attending_employees table > corresponding employee details form 'employee' table), what team they belong to (from the club_teams table) and the event details from the 'club_events' table).
Currently I am using multiple mysqli queries to display this information however cannot get my head around pulling the data from the database in one query (ie: LEFT JOIN). Your assistance would be greatly appreciated!
Below are the queries i am currently using:
$query = msqli_query($con, "SELECT * FROM attending_employees")or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){
while($attending = mysqli_fetch_array($query)){
foreach($attending['club_event']){
$eventid = $attending['club_event'];
$query = msqli_query($con, "SELECT * FROM club_events WHERE club_event_id = '$eventid'")or die(mysqli_error($con));
while($event_details = mysqli_fetch_array($query)){
// Echo event details
}
}foreach($attending['employee']){
$empid = $attending['employee'];
$query = msqli_query($con, "SELECT * FROM employees WHERE employee_id = '$empid'")or die(mysqli_error($con));
while($event_employees = mysqli_fetch_array($query)){
// Echo employee details
}
}foreach($attending['team']){
$teamid = $attending['team'];
$query = msqli_query($con, "SELECT * FROM club_teams WHERE clb_team_id = '$teamid'")or die(mysqli_error($con));
while($event_team = mysqli_fetch_array($query)){
// Echo team details
}
}
}
}
This method is highly inefficient and wasteful since its retrieving duplicate data (ie: all repeated 'club_event_id's in the 'attending_employees' table.)
Try this:
$query = msqli_query(
$con,
"SELECT"
. " attending_employees.*"
. ", club_events.*"
. ", employees.*"
. ", club_teams.*"
. " FROM"
. " attending_employees"
. " LEFT JOIN club_events ON club_events.club_event_id = attending_employees.club_event"
. " LEFT JOIN employees ON employees.employee_id = attending_employees.employee"
. " LEFT JOIN club_teams ON club_teams.clb_team_id = attending_employees.team"
) or die(mysqli_error($con));
I have this query:
$query = "SELECT ads.*,
trafficsource.name AS trafficsource,
placement.name AS placement,
advertiser.name AS advertiser,
country.name AS country
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
JOIN placement ON ads.placementId = placement.id
JOIN advertiser ON ads.advertiserId = advertiser.id
JOIN country ON ads.countryId = country.id
WHERE advertiserId = '$advertiser_id'";
and ads table
ads Table
ad_id PK
size
price
trafficsourceId FK
placementId FK
advertiserId FK
countryId FK
For getting data I'm using
$result = mysql_query($query) or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
}
I cant figure out how I need to print page so that it's not looking like rows but also need id's of for example trafficsource name. I want to make something like that:
EDITED:
<div id="adscontent">
<h1>Advertiser:</h1> Advertiser name
<h2>Traffic Sources:</h2> Company1, Company2, Company 3
<h2>Placements:</h2> Like: Newspaper, radio, website, bla bla
</div>
Thanks
You will need to play around with the printout but I think something like this will work:
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[$row['advertiser']]['countries'][] = $row['country'];
$results[$row['advertiser']]['trafficsources'][] = $row['trafficsource'];
$results[$row['advertiser']]['placements'][] = $row['placement'];
}
// And now print the data
foreach ($results as $arvertiser => $data)
{
echo "<h1>{$advertiser}</h1>";
// Print Placements
echo "Placements: " . implode(", ", $data['placements']) . '<br />;
// Print Countries
echo "Countries: " . implode(", ", $data['countries']) . '<br />;
// Print Placements
echo "Traffic Sources: " . implode(", ", $data['trafficsources']) . '<br />;
}
EDIT: If you need to add the IDs you will need to change your select to:
$query = "SELECT ads.*,
trafficsource.name AS trafficsource,
trafficsource.id AS trafficsourse_id,
placement.name AS placement,
placement.id AS placement_id,
advertiser.name AS advertiser,
advertiser.id AS advertiser_id,
country.name AS country
country.id AS country_id
FROM ads
JOIN trafficsource ON ads.trafficsourceId = trafficsource.id
JOIN placement ON ads.placementId = placement.id
JOIN advertiser ON ads.advertiserId = advertiser.id
JOIN country ON ads.countryId = country.id
WHERE advertiserId = '$advertiser_id'";
From then on you can include this information in the $results array like so:
$results[$row['advertiser']['countries'] = array(
'id' => $row['country_id'],
'value' => $row['country')
);
and print out whatever you need from there.