join issue MYSQL/PHP - php

i have a bit of a problem, ive never used JOIN before, and this is the first time, and i got into some problems:
<?php
//$count to keep the counter go from 0 to new value
$count=0;
//I need to select the level for the users building first, meanwhile i also
//need to get the money_gain from the table buildings, which is a table that
//is common for each member, which means it doesnt have a userid as the other table!
//And then for each of the buildings there will be a $counting
$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user");
while($row = mysql_fetch_assoc($qu1))
{
$count=$count+$row['level'];
echo $row['level'];
}
?>
So basically ive heard that u should tie them together with a common column but, in this case thir isnt any.. im just lost right now?
EDIT Oh right, I need the right level to be taken out with the correct money_gain too, in building_user its 'buildingid'and in buildings, its just 'id'! have no idea how to make a common statement though!

From your edit,
SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;
You essentially get the records for the user joining them at the building id
Performance-wise, joins are a better choice but for lightweight queries such as this, the query above should work fine.
You can also give each column a neater name
SELECT building_user.level as level,buildings.money_gain as money gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;
and access them as
$level = $row['level'];
$gain = $row['gain'];

i think you problem is, that MySQL doesn't know how to JOIN the two Tables. Therefor you have to tell MySQL how to do that.
Example
SELECT * FROM TABLE1 INNER JOIN Table1.col1 ON TABLE2.col2;
where col1 and col2 are the columns to join (a unique identifier)

<?php
$count=0;
$qu1 = mysql_query("SELECT bu.level, bs.money_gain FROM building_user bu, buildings bs WHERE bu.userid=$user");
while($row = mysql_fetch_assoc($qu1))
{
$count=$count+$row['level'];
echo $row['level'];
}
?>

Try this
$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain
FROM building_user
JOIN buildings ON building_user.building_id = buildings.id
WHERE building_user.userid=$user");
building_user.building_id is the foreght key of table building_user and
buildings.id is the primary key of table buildings

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.

Left join MySql/PHP

Whilst populating a table based on ids and labels from different tables, it appeared apparent there must potentially be a better way of achieving the same result with less code and a more direct approach using LEFT JOIN but i am puzzled after trying to work out if its actually capable of achieving the desired result.
Am i correct in thinking a LEFT JOIN is usable in this instance?
Referencing two tables against one another where one lists id's related to another table and that other table has the titles allocated for each reference?
I know full well that if theres independent information for each row LEFT JOIN is suitable, but where theres in this case only several ids to reference for many rows, i just am not clicking with how i could get it to work...
The current way i am achieving my desired result in PHP/MySQL
$itemid = $row['item_id'];
$secid = mysql_query(" SELECT * FROM item_groups WHERE item_id='$itemid' ");
while ($secidrow = mysql_fetch_assoc($secid)) {
//echo $secidrow["section_id"]; //testing
$id = $secidrow["section_id"];
$secnameget = mysql_query(" SELECT * FROM items_section_list WHERE item_sec_id='$id' ");
while ($secname = mysql_fetch_assoc($secnameget)) {
echo $secname["section_name"];
}
}
Example of the data
Item groups
:drink
:food
:shelf
Item List
itemId, groupId
Group List
groupId, groupTitle
The idea so outputting data to a table instead of outputting "Item & Id Number, in place of the ID Number the title actually appears.
I have achieved the desired result but i am always interested in seeking better ways to achieve the desired result.
If I've deciphered your code properly, you should be able to use the following query to get both values at the same time.
$itemid = $row['item_id'];
$secid = mysql_query("
SELECT *
FROM item_groups
LEFT JOIN items_section_list
ON items_section_list.item_sec_id = item_groups.section_id
WHERE item_id='$itemid'
");
while ($secidrow = mysql_fetch_assoc($secid)) {
//$id = $secidrow["section_id"];
echo $secidrow["section_name"];
}

sql using LIKE clause : php

I'm trying to generate a list of events that a user is attending. All I'm trying to do is search through columns and comparing the userid to the names stored in each column using LIKE.
Right now I have two different events stored in my database for testing, each with a unique eventID. The userid i'm signed in with is attending both of these events, however it's only displaying the eventID1 twice instead of eventID1 and eventID2.
The usernames are stored in a column called acceptedInvites separated by "~". So right now it shows "1~2" for the userid's attending. Can I just use %like% to pull these events?
$userid = $_SESSION['userid'];
echo "<h2>My Events</h2>";
$myEvents = mysql_query("select eventID from events where acceptedInvites LIKE '%$userid%' ");
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
My output is just 11 when it should be 12
Change your table setup, into a many-to-many setup (many users can attend one event, and one user can attend many events):
users
- id (pk, ai)
- name
- embarrassing_personal_habits
events
- id (pk, ai)
- location
- start_time
users_to_events
- user_id ]-|
|- Joint pk
- event id ]-|
Now you just use joins:
SELECT u.*
FROM users u
JOIN users_to_events u2e
ON u.id = u2e.id
JOIN events e
ON u2e.event_id = e.id
WHERE u.id = 11
I'm a bit confused by your description, but I think the issue is that mysql_fetch_array just returns one row at a time and your code is currently set up in a way that seems to assume $fetch is filled with an array of all the results. You need to continuously be calling mysql_fetch_array for that to happen.
Instead of
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
You could have
while ($row = mysql_fetch_array($myEvents)) {
echo $row['eventID'];
}
This would cycle through the various rows of events in the table.
Instead of using foreach(), use while() like this:
$myEvents = mysql_query("SELECT `eventID` FROM `events` WHERE `acceptedInvites` LIKE '".$userid."'");
while ($fetch = mysql_fetch_array($myEvents))
{
echo $fetch['eventID'];
}
It will create a loop like foreach() but simpler...
P.S. When you make a MySQL Query, use backticks [ ` ] to ensure that the string is not confused with MySQL functions (LIKE,SELECT, etc.).

Foreach or Inner join? -- that is the PHP question

I have 2 tables. One (artWork) with all the data I want to pull from, including 2 cols of id's. The other (sharedWork) has the same 2 id cols that are also in the first -- but none of the essential data I want to echo out. Objective: use the id's in both table to filter out row in the first (artWork). See below in the code what I tried that didn't work
I also tried to figure out an inner join that would accomplish the same. No luck there either. Wondering which would be the best approach and how to do it.
thanks
Allen
//////// Get id's first ///////////
$QUERY0="SELECT * FROM artWork WHERE user_id = '$user_id' ";
$res0 = mysql_query($QUERY0);
$num0 = mysql_num_rows($res0);
if($num0>0){
while($row = mysql_fetch_array($res0)){
$art_id0 = $row['art_id'];
}
}
$QUERY1="SELECT * FROM shareWork WHERE user_id = '$user_id' ";
$res1 = mysql_query($QUERY1);
$num1 = mysql_num_rows($res1);
if($num1>0){
while($row = mysql_fetch_array($res1)){
$art_id = $row['art_id'];
}
}
$art_id2 = array_merge($art_id0, $art_id1);
foreach ($art_id2 as $art_id3){
$QUERY="SELECT * FROM artWork WHERE art_id = '$art_id3' ";
// echo "id..".$art_id0;
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$art_title = $row['art_title'];
$art_id = $row['art_id'];
etc................and so on
.........to....
</tr>";
}
}
}
Don't query your database inside a loop unless you absolutely have to.
Everytime you query the database, you're using disk I/O to read through the database and return your record. Disk I/O is the slowest read on a computer, and will be a massive bottleneck for your application.
If you run larger queries upfront, or at least outside of a loop, you will hit your disk less often, improving performance. Your results from larger queries will be held in memory, which is considerably faster than reading from disk.
Now, with that warning out of the way, let's address your actual problem:
It seems you're trying to grab records from artWork where the user is the primary artist, or the user was one of several artists to work on a group project. artWork seems to hold the id of the primary artist on the project whereas shareWork is probably some sort of many-to-many lookup table which associates user ids with all art projects they were a part of.
The first thing I should ask is whether or not you even need the first query to artWork or if the primary artist should have a record for that art_id in shareWork anyway, for having worked on the project at all.
If you don't need the first lookup, then the query becomes very easy: just grab all of the users art_ids from shareWork table and use that to lookup the his or her records in the main artWork table:
SELECT artWork.*
FROM artWork
WHERE art_id IN
(SELECT art_id
FROM shareWork
WHERE user_id = $user)
If you do need to look in both tables, then you just add a check in the query above to also check for that user in the artWork table:
SELECT artWork.*
FROM artWork
WHERE
user_id = $user
OR art_id IN
(SELECT art_id
FROM shareWork
WHERE user_id = $user)
This will get you all artWork records in a single query, rather than.. well, a lot of queries, and you can do your mysql_fetch_array loop over the results of that one query and be done with it.

Categories