MySQL Inner join output to html table in php - php

I have a table that is being displayed in a form, which looks like this: http://puu.sh/5VBBv.png
The end of the table, City, is displaying an ID of a city, which is supposed to be linked to another table (http://puu.sh/5VBIG.png).
What I've done for my INNER JOIN query is:
mysql_query("SELECT * FROM cities INNER JOIN people ON people.cityid = cities.id") or die(mysql_error());`
and I'm trying to output it into a table:
echo "<td>" . $row['cityid'] . "</td>";
My issue is that I'm not quite sure how to actually display the cityid that corresponds to the city name. I've tried using ['name'] and other values as the value to output in the table, and I can't find any solution for this anywhere so far. I'm just learning joins, so I don't exactly have any knowledge on what I could be doing wrong. Is there anything immensely obvious?

First your use of * in the join query could be ambiguous. If cities had a name column and people had a name column, you won't know which one you're getting. Second you can do this a couple ways. I think you're trying to get a city id from a city name. If that's correct you can either make and ajax call and query it directly or define an array as follow:
$res = mysql_query("...");
$city_ids = Array();
while ($ary = mysql_fetch_assoc($res)) {
city_ids[$ary['name']] = Ary['id'];
}
Then when you get the name, you just loop up $ary['name'].

Selecting from people and joining cities makes more sense. Then select the fields you need.
SELECT people.*, cities.name as city_name FROM people JOIN cities ON people.cityid = cities.id
Then, echo $row['city_name']

Select ID from cities city, people person where person.ID = city.ID
You are selecting the ID from both Cities and People, and joining on the ID

Related

SQL displaying multiple records

I am currently working on a school time-table management system wherein the student dashboard, Time-table is displayed according to the current day, but when displaying the data, two duplicates come out of nowhere.
Initially, I joined the tables 'students' and 'timetable' through an 'INNER JOIN', but the problem with it was duplicates being placed simultaneously which was later fixed with 'RIGHT JOIN'.
Now, the duplicates display after the entire table has been printed.
HERE IS THE CODE BELOW:-
<?php
require_once("connection.php");
function information($subject, $time, $day, $teacher){
$element = "
<tr>
<td>$subject</td>
<td>$time</td>
<td>$day</td>
<td>$teacher</td>
</tr>
";
echo $element;
}
function getData(){
global $conn;
$sql = '
SELECT DISTINCT students.roll_no
, students.class_room
, timetable.subject_name
, timetable.time_code
, timetable.day_otw
, timetable.teacher_name
FROM students
RIGHT
JOIN timetable
ON students.class_room = timetable.room_no;
';
$result = mysqli_query($conn, $sql);
$mydate=getdate(date("U"));
if(mysqli_num_rows($result) > 0){
while($row=mysqli_fetch_assoc($result)){
if($mydate['weekday'] == $row['day_otw']){
information($row['subject_name'], $row['time_code'], $row['day_otw'], $row['teacher_name']);
}
}
} else {
echo "
<h1 class=\"check-data\">Sorry, You haven't been assigned a class yet!</h1>
<h3 class=\"ask\">Please contact your teacher/supervisor for more information.</h3>
";
}
}
getData();
?>
SO BASICALLY THE ENTIRE TABLE IS BEING DUPLICATED TWICE.
Outer joining makes no sense here. You neither want students without a timetable entry (LEFT OUTER JOIN), nor timetable entries without students (RIGHT OUTER JOIN). Then you are using DISTINCT because you are fightig duplicates, which is a bad idea, because thus you don't examine where the duplicates stem from. There should be no duplicates in the first place, so probably there is something wrong with the join criteria or data. You should fix this instead of looking for inappropriate workarounds.
Your join criteria is that the student is in the same room as the timetable entry. Why is the student associated a room? Do all the student's classes take place in the same room? In that case, yes, a class room would mean a class and then the tables would be related by the class (room). But if that were the case, you would get no duplicates.
I assume there to be something else to relate students with the timetable. Look for a student ID in the timetable. Something like:
SELECT s.roll_no, s.class_room, t.subject_name, t.time_code, t.day_otw, t.teacher_name
FROM students s
JOIN timetable t ON s.student_id = t.student_id
ORDER BY s.student_id, t.day_otw, t.time_code;
Or maybe there is something like an additional class ID, both student and timetable belong to? (The room in both tables would look strange then, however.) Maybe you don't know the database well enough. If this is the case, ask somebody who does.
From your screen, you only need to display timetable data, so there is no point to link to student table
Please consider using the following instead of your right join
SELECT
timetable.subject_name, timetable.time_code,
timetable.day_otw, timetable.teacher_name
FROM timetable

How to user SQL two table field.? PHP

Here I want to access two table field but I cant get success. Here is my little code. please check that. I want to access Analysis.Right and tabl3.right.
I am printing its with foreach loop. like $res['Right'] of Analysis and $res['right'] of tabl3. when I try to print this it's show me error
Undefind index Right.
any one can help me
$qry = "select Analysis.Q_Id, tabl3.Q_Id, Analysis.Right, tabl3.right from tabl3 INNER JOIN Analysis ON Analysis.Q_Id = tabl3.Q_Id where Analysis.Q_Id = 3";
please help..
you have tow column with right name related to different table so there is not a column name right but 'Analysis.Right ' or 'tabl3.right'
or you can assign an alias for set the column name equalt to Right where you need .. eg:
$qry = "select
Analysis.Q_Id
, tabl3.Q_Id
, Analysis.Right as Right
, tabl3.right as Right_t3
from tabl3
INNER JOIN Analysis ON Analysis.Q_Id = tabl3.Q_Id where Analysis.Q_Id = 3";
Your result set has columns with the same name. Give them different names:
select t3.Q_Id, a.Right as a_right, t3.right as t3_right
from tabl3 t3 inner join
Analysis a
on a.Q_Id = t3.Q_Id
where a.Q_Id = 3;
When you look for the names in your code, look for a_right and t3_right.
Note that you don't need to return Q_Id twice. The ON clause guarantees that the values are the same.

echoing data From mySQL when table column joined twice

I am trying to echo both the employee name and manager name
SQL QUERY:
SELECT *
FROM `form`
INNER JOIN `emp` AS employee
ON `form`.emp_ID = employee.emp_ID
INNER JOIN `emp` AS manager
ON `form`.manager_ID = manager.emp_ID
ECHO:
while($row = $result->fetch_assoc()){
echo $row['emp_name'];
}
Always outputs the managers name.
have tried the following:
$row['employee.emp_name']
$row['employee']['emp_name']
which all don't work.
any help is appreciated
When the columns have the same name, their values will overlap when retrieving by fetch_assoc(). You can either use fetch_array() and reference the columns by numeric index (not recommended with SELECT *, since you can't easily guarantee the order of columns), or you will have to list the column names explicitly and alias them. For example:
SELECT emp.emp_name emp_emp_name, manager.emp_name manager_emp_name, ...
This would give you separate distinctly named fields in the result, that you could then access from what fetch_assoc() returns.

How to Output the results of a MySQL query that used aliases?

I have two primary MySQL tables (profiles and contacts) with many supplementary tables (prefixed by prm_). They are accessed and manipulated via PHP.
In this instance I am querying the profiles table where I will retrieve an Owner ID and a Breeder ID. This will then be referenced against the contacts table where the information on the Owners and Breeders is kept.
I received great help here on another question regarding joins and aliases, where I was also furnished with the following query. Unfortunately, I am having huge difficulty in actually echoing out the results. Every single site that deals with Self Joins and Aliases provide lovely examples of the queries - but then skip to "and this Outputs etc etc etc". How does it output????
SELECT *
FROM (
SELECT *
FROM profiles
INNER JOIN prm_breedgender
ON profiles.ProfileGenderID = prm_breedgender.BreedGenderID
LEFT JOIN contacts ownerContact
ON profiles.ProfileOwnerID = ownerContact.ContactID
LEFT JOIN prm_breedcolour
ON profiles.ProfileAdultColourID = prm_breedcolour.BreedColourID
LEFT JOIN prm_breedcolourmodifier
ON profiles.ProfileColourModifierID = prm_breedcolourmodifier.BreedColourModifierID
) ilv LEFT JOIN contacts breederContact
ON ilv.ProfileBreederID = breederContact.ContactID
WHERE ProfileName != 'Unknown'
ORDER BY ilv.ProfileGenderID, ilv.ProfileName ASC $limit
Coupled with this is the following PHP:
$owner = ($row['ownerContact.ContactFirstName'] . ' ' . $row['ownerContact.ContactLastName']);
$breeder = ($row['breederContact.ContactFirstName'] . ' ' . $row['breederContact.ContactLastName']);
All details EXCEPT the contacts (gender, colour, etc.) return fine. The $owner and $breeder variables are empty.
Any help in settling this for me would be massively appreciated.
EDIT: My final WORKING query:
SELECT ProfileOwnerID, ProfileBreederID,
ProfileGenderID, ProfileAdultColourID, ProfileColourModifierID, ProfileYearOfBirth,
ProfileYearOfDeath, ProfileLocalRegNumber, ProfileName,
owner.ContactFirstName AS owner_fname, owner.ContactLastName AS owner_lname,
breeder.ContactFirstName AS breeder_fname, breeder.ContactLastName AS breeder_lname,
BreedGender, BreedColour, BreedColourModifier
FROM profiles
LEFT JOIN contacts AS owner
ON ProfileOwnerID = owner.ContactID
LEFT JOIN contacts AS breeder
ON ProfileBreederID = breeder.ContactID
LEFT JOIN prm_breedgender
ON ProfileGenderID = prm_breedgender.BreedGenderID
LEFT JOIN prm_breedcolour
ON ProfileAdultColourID = prm_breedcolour.BreedColourID
LEFT JOIN prm_breedcolourmodifier
ON ProfileColourModifierID = prm_breedcolourmodifier.BreedColourModifierID
WHERE ProfileName != 'Unknown'
ORDER BY ProfileGenderID, ProfileName ASC $limit
Which I could then output by:
$owner = ($row['owner_lname'] . ' - ' . $row['owner_fname']);
Many Thanks to All!
I guess you're using the mysql_fetch_array or the mysql_fetch_assoc-functions to get the array from the result-set?
In this case, you can't use
$row['ownerContact.ContactFirstName']
as the PHP-Docs read:
If two or more columns of the result have the same field names, the
last column will take precedence. To access the other column(s) of the
same name, you must use the numeric index of the column or make an
alias for the column. For aliased columns, you cannot access the
contents with the original column name.
So, you can either use an AS in your SQL-query to set other names for the doubled rows or use the numbered indexes to access them.
This could then look like this:
Using AS in your Query
In your standard SQL-query, the columns in the result-set are named like the columns which their values come from. Sometimes, this can be a problem due to a naming-conflict. Using the AS-command in your query, you can rename a column in the result-set:
SELECT something AS "something_else"
FROM your_table
This will rename the something-column to something_else (you can leave the ""-quotes out, but I think it makes it more readable).
Using the column-indexes for the array
The other way to go is using the column-index instead of their names. Look at this query:
SELECT first_name, last_name
FROM some_table
The result-set will contain two columns, 0 ==> first_name and 1 ==> last_name. You can use this numbers to access the column in your result-set:
$row[0] // would be the "first_name"-column
$row[1] // would be the "last_name"-column
To be able to use the column-index, you'll need to use mysql_fetch_row or the mysql_fetch_assoc-function, which offers an associative array, a numeric array, or both ("both" is standard).
you need to replace the * with the data you need , and the similar ones you have to make aliases too :
ownerContact.ContactFirstName as owner_ContactFirstName
and
breederContact.ContactFirstName as breeder_ContactFirstName .
like this :
select ownerContact.ContactFirstName as owner_ContactFirstName , breederContact.ContactFirstName as breeder_ContactFirstName from profiles join ownerContact ... etc
in this way you will write :
$owner = ($row['owner_ContactFirstName'] . ' ' . $row['owner_ContactLastName']);
$breeder = ($row['breeder_ContactFirstName'] . ' ' . $row['breeder_ContactLastName']);
You cannot specify table alias when you access row using php. Accessing it by $row['ContactFirstName'] would work if you didn't have 2 fields with the same name. In this case whatever ContactFirstName appears second overwrites the first.
Change your query to use fields aliases, so you can do $owner = $row['Owner_ContactFirstName'].
Another option I'm not 100% sure is to access field by index, not by name(e.g. $owner=$row[11]). Even if it works I don't recommend to do so, you will have a lot of troubles if change your query a bit.
On outer select You have only two tables:
(inner select) as ilv
contacts as breederContact
there is no ownerContact at all

How to select value from a drop-down list, get the corresponding values from another table, then put those into another drop-down list?

Ok, here's a database.
http://i.stack.imgur.com/j05AB.png
Say I've inserted values into the database for each of these tables, although the IDs would be auto incrementing. There are many BVALUES from each AVALUE, thus the AB table. I have all the AVALUEs from TABLE A in a drop-down list. A user selects an AVALUE which I put into a variable using
$AVALUE = $_POST['AVALUE']
Then I do an sql statement to get the AVALUEs from TABLE A that equal $AVALUE.
$sql = "SELECT AVALUE FROM TABLEA WHERE" . $AVALUE . " = AVALUE";
How do I then get the NAMEID from TABLEA for that AVALUE, then reference to AB where TABLEANAMEID = NAMEID from TABLEA? Then I want to get all the BVALUES by getting all the TABLEBNAMEIDs that correspond to the TABLEANAMEIDs.
I then want those BVALUES in a drop-down list on a seperate HTML page. After a bit of Googling the solution I think would be to do some sort of a loop putting the BVALUES into a variable as all the NAMEIDs from TABLE B increment where the variable would be in an $BVALUE loop and the list values would show with all the BVALUES.
I hope I explained that right. I think I know what I'm trying to do but I have no idea how to actually implement it. Please help guys.
You need to join those table together. What you are describing is an m:n relation. In this case you have do use 2 joins like this:
SELECT * FROM TableA AS a WHERE a.avalue = $AVALUE
JOIN TableAB AS a2b ON a.namevalue = a2b.id_a
JOIN TableB AS b ON a2b.id_b = b.id
Maybe u means, u want to get all BVALUE which has relation with selected AVALUE in table AB
$sql = "SELECT B.NAMEID as id, BVALUE as value FROM TABLEA A
LEFT JOIN AB ON TABLEANAMEID=A.NAMEID
LEFT JOIN TABLEB B ON TABLEBNAMEID=B.NAMEID
WHERE AVALUE = $AVALUE";`
get mysql result
$result = mysql_query($sql);
iterate
echo "<select>";
foreach ($r = mysql_fetch_object($result)) {
echo '<option value="'.$r->id.'">'.$r->value.'</option>';
}
echo "</select>";

Categories