MySQL database primary key usage - php

I am designing a MYSQL database for online tutoring website
Let's say, I have:
faculty table with (faculty_id, faculty name)
subject table with (subject_id, subject name)
student table with (student_id, student name)
class table with (class_id, faculty_id, student_id, subject_id)
Now I would like to run SQL queries on the class table to find out all students enrolled with a particular faculty & under a particular subject for which I have:
$sql=("SELECT *
FROM class
WHERE (faculty_id = '" . mysql_real_escape_string($_POST['faculty_id']) . "')
and (subject_id = '" . mysql_real_escape_string($_POST['subject_id']) . "')");
However, I can't seem to figure out how to retrieve student name, faculty name, and subject name instead of just the faculty_id, student_id & subject_id stored in the class table.
Is there some type of SCHEMA and foreign key relations I need to create which automatically link the ID numbers to their respective rows in the respective tables so i can run UPDATE, DELETE, and INSERT queries based on these ID numbers?
Am I missing something important here? I'm not an expert in DB design. Please help.

That's not something that happens in your schema, it's something that you do when you query the database.
To get information from a related table, you JOIN that table.
SELECT
class.class_id,
student.name AS `student_name`,
faculty.name AS `faculty_name`,
subject.name AS `subject_name`
FROM
class
INNER JOIN
student
ON
student.student_id = class.student_id
INNER JOIN
faculty
ON
faculty.faculty_id = class.faculty_id
INNER JOIN
subject
ON
subject.subject_id = class.subject_id
WHERE
class.faculty_id = ?
AND
class.subject_id = ?
You'll have to replace any column names with what they actually are (your examples had spaces in them, so I'm sure those aren't the real names), and put your PHP code with the post values where the ? are... good time to read up on PDO parameterized queries too.

$sql=("SELECT * FROM class c, student s WHERE (c.faculty_id = '" . mysql_real_escape_string($_POST['faculty_id']) . "') and (c.subject_id = '" . mysql_real_escape_string($_POST['subject_id']) . "') and s.student_id = c.student_id");
You need to also select values from the table student.

Related

PHP PDO Multiple Table join

I have multiple tables and I want to access the fields in a specific table. Here are the table schemas:
Each tbl_acct has one tbl_unit. A tbl_unit has many tbl_groups and a tbl_groupcontact consist of the contacts and the related group. Every time I log in, I set a session where $_SESSION['unitid'] = $row['unitid'];.
What I wanted to do is to access the fields in the tbl_contacts. For now my code is here:
$data = $conn->prepare("SELECT * FROM tbl_groups LEFT JOIN tbl_groupcontact ON tbl_groups.id=tbl_groupcontact.group_id WHERE tbl_groups.unitid = ?");
$data->execute(array($_SESSION['unitid']));
foreach ($data as $row) {
echo $row['fname'] . " " . $row['lname']. "<br />";
}
As you can see, I can related the tbl_groups and tbl_groupcontact in my code however, I can't get the fields in the tbl_contacts. Am I missing something here? Any help would be much appreciated.
You need to join another table.
SELECT tbl_contacts.*
FROM tbl_groups
INNER JOIN tbl_groupcontact ON tbl_groupcontact.group_id = tbl_groups.id
INNER JOIN tbl_contacts ON tbl_contacts.id = tbl_groupcontact.contact_id
WHERE tbl_groups.unitid = ?
No need for (slower) LEFT JOIN btw - use it when you want to retrieve records from (left-side) table even when there's no match found in joined (right-side) table (it's columns will be filled with nulls in this case).

MySQL Inner join output to html table in 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

SELECT data via array from different tables in mysql

hello guys i found some similar questions here but nothing work's for me maybe someone can help me.
i have a couple of filter where the user can list other users by properties like in a dating site. i want to show the user just the members from the filters the user choose. i store the keywords in an array and want to get the data now from two different tables.
at the moment i use this query but its just shows me the values from one table
$sql = "SELECT * FROM users WHERE username IN ($data) AND country IN ($data) OR city IN ($data) OR gender IN ($data)";
i need to get some more properties like smoker or non smoker etc. from another table how would i do this with this array ($data). sorry for the bad english
the table one is users who contains id, username, gender, country
and the other table called properties who contains id, userid, hobbies, jobs i need to join them somehow
Use JOIN on their "linked" column :
$sql = " SELECT u.username, u.country ";
$sql .= " FROM users u ";
$sql .= " LEFT OUTER JOIN other_table t ON u.id = t.id";
$sql .= " WHERE username IN ($data) AND country IN ($data) OR city IN ($data) OR gender IN ($data)";
MySQL documentation.

Copy one table to another with different colum count

As i am far from an expert in php this got me stunned and i can't seem to make a script for it.
Lets see if i can explain this as clearly as possible.
Lets say i have table1 and table2
Table1 = (teamid, name, round1pos, round1score, round2pos, round2score)
Table2 = (id, tournamentid, teamid, name, round1pos, round1score, round2pos, round2score...till round10pos/round10score)
When copied from table1 to table 2 i want to add 2 fields in front of it. (id and tournamentid)
The problem i am facing is that Table1 has a different amount of roundxpos/roundxscore each time.
Basically what i want to do is once a tournament is over i want to delete the table. but copy the data inside it to another table to archive the results. but each tournament can have a different size of rounds.
I hope someone can understand what i am trying to achieve +_+.
You should create a third table, remove the roundX columns from your existing tables and reference them with their IDs.
rounds: team_id, tournament_id, no, pos, score
You should normalize your tables but in the meantime....
I'm assuming the main problem is handling the variable number of roundxpos and roundxscore columns in the code.
Hope this helps:
Get the results of this query: SHOW COLUMNS FROM Table1 WHERE Field LIKE 'round%pos'
Get the results of this query: SHOW COLUMNS FROM Table1 WHERE Field LIKE 'round%score'
Create the table2 inserts by looping through field names
//example, assuming results are fetched into an associative array
$query = "INSERT INTO table2 (tournamentid, teamid, name)";
foreach($roundpos_fields as $f){ $query .= "," . $f['Field']; }
foreach($roundscore_fields as $f){ $query .= "," . $f['Field']; }
$query .= "( SELECT $tournamentid, '' teamid, name";
foreach($roundpos_fields as $f){ $query .= "," . $f['Field']; }
foreach($roundscore_fields as $f){ $query .= "," . $f['Field']; }
$query .= ")";

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

Categories