PHP mysql Select query calling more than specified data - php

I've been working and testing with queries, and I came across this issue which I don't understand why it's happening.
I have this code:
<?php
$query = "
SELECT sc.course_code
, c.course_name
FROM student_course sc
, courses c
WHERE sc.course_code= 'MC 101'
AND sc.id_num='A0001'
";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<p> <h4 style="w3-wide"> <?php echo $row["course_name"];?> </h3>
<h4 style="w3-wide"><?php echo $row["course_code"];?> </h3>
<button type="button" class="w3-button w3-theme-d2 w3-margin-bottom" style = "float:right"><i></i> View Course</button></p>
<br>
And based on what I know, it should call a single data which satisfies the conditions student_course.course_code = 'MC 101' and student_course.id_num='A0001' which should only be
Statistics in Computing
MC 101
However, this is what I'm getting:
The course names are correct, but all of them have the same code. Does anyone know why this is happening? Much appreciated!

You missed a join condition,
it must me something like ON sc.course_id = c.id
SELECT sc.course_code, c.course_name
FROM student_course sc
JOIN courses c ON sc.course_id = c.id
WHERE sc.course_code= 'MC 101'
AND sc.id_num='A0001'

Related

How to echo second column with only the primary key - SQL/PHP

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']; ?>

Showing Data with 2 tables on php mysql

I have a problem with showing data from 2 tables
Table 1 (kegiatan): id_kgt (PK), nama_kgt,ket, tg_mulai, tg_akhir, nm_pengirim, indi01, indi02, indi03, indi04, indi05, indi06, indi07, indi08, indi09, indi010,
Table 2 (pilihan): kdpilih (PK), nmpilih
kdpilih contain number which linked with indi01 to indi010
nmpilih contain plain text, ex: kdpilih: 1 = nmpilih: car
I already create the script, but the problem is when someone entry the data less or more than 3 field (indi01, indi02, indi03) from the entry page it will show nothing. Is there any solution to fix this? Is my join tables script wrong? So, i want showing all the data although the data on entry page only 1, 2, 3 or etc.
This is my script, any help wil so helpfull. Thanks
<?php
$sql = "
SELECT a.id_kgt
, a.nama_kgt
, a.ket
, a.tg_mulai
, a.tg_akhir
, a.nm_pengirim
, a.file
, b.nmpilih AS indi01
, c.nmpilih AS indi02
, d.nmpilih as indi03
FROM kegiatan a
JOIN pilihan b
ON b.kdpilih = a.indi01
JOIN pilihan c
ON c.kdpilih = a.indi02
JOIN pilihan d
ON d.kdpilih = a.indi03
ORDER
BY a.id_kgt ASC
";
$result = mysqli_query($conn, $sql);
$no = 1;
if (mysqli_num_rows($result) > 0)
{
while ($data = mysqli_fetch_array($result))
{
echo "<tr>
<td>".$data['id_kgt']."</a></td>
<td>".$data['nama_kgt']."</a></td>
<td>".$data['ket']."</td>
<td>".tglindo($data['tg_mulai'])."</td>
<td>".tglindo($data['tg_akhir'])."</td>
<td>".$data['indi01'].", ".$data['indi02'].", ".$data['indi03']."</td>
<td>".$data['nm_pengirim']."</td>
<td>
<a href='".$data['file']."'>Download</a>
<a href='kegiatan_ubah.php?id_file=$data[id_kgt]'>Ubah</a>
<a href='kegiatan_hapus.php?id_file=$data[id_kgt]'>Hapus</a>
</td>
</tr>";
$no++;
}
}
else
{
echo "No data.";
}
If you want to show the data on the other tables do not do a join, you may consider left join instead.
Cheers
SOLVED
i use this magic:
"SELECT a.id_kgt, a.nama_kgt, a.ket, a.tg_mulai, a.tg_akhir, a.nm_pengirim, a.file,
b.nmpilih as indi01, c.nmpilih as indi02, d.nmpilih as indi03, e.nmpilih as indi04, f.nmpilih as indi05,
g.nmpilih as indi06, h.nmpilih as indi07, i.nmpilih as indi08, j.nmpilih as indi09, k.nmpilih as indi010
FROM kegiatan a
LEFT JOIN pilihan b ON b.kdpilih = a.indi01 LEFT JOIN pilihan c ON c.kdpilih = a.indi02
LEFT JOIN pilihan d ON d.kdpilih = a.indi03 LEFT JOIN pilihan e ON e.kdpilih = a.indi04
LEFT JOIN pilihan f ON f.kdpilih = a.indi05 LEFT JOIN pilihan g ON g.kdpilih = a.indi06
LEFT JOIN pilihan h ON h.kdpilih = a.indi07 LEFT JOIN pilihan i ON i.kdpilih = a.indi08
LEFT JOIN pilihan j ON j.kdpilih = a.indi09 LEFT JOIN pilihan k ON k.kdpilih = a.indi010
ORDER BY a.id_kgt ASC"

Mysql query returning too many rows

so I have 3 tables all inner joined, I am trying to put discussions with the discussion topic on my main page, with the users name and the latest discussion message on the main page as well.
THE PROBLEM: The query is returning all messages attached to all the discussions.....I just need the last message associated with the discussion returned.
I have been at this all day and cant figure it out. I have tried group by but that just gave me an error on mysqli_fetch_array
Here is my code
$discussionquery = "SELECT discussion_messages.discussion_id, user_profile.first_name, user_profile.last_name, discussion_messages.message_text, case_discussion.discussion_title
FROM `user_profile`
INNER JOIN discussion_messages
ON (user_profile.user_id = discussion_messages.user_id)
INNER JOIN case_discussion
ON (case_discussion.discussion_id = discussion_messages.discussion_id)
WHERE discussion_messages.case_id = '$thecaseid'
ORDER BY discussion_messages.message_id DESC";
$discussionquerydata = mysqli_query($dbc, $discussionquery);
while ($row2 = mysqli_fetch_array($discussionquerydata)) {
$discussion_id = $row2['discussion_id'];
?>
<!-- Begin Recent Discussions -->
<div class="row">
<a href="discussion.php?newfact=$thecaseid'>">
<div class="col-xs-4 col-md-2">
<img src="img/client4.jpg" class="profile_picture img-rounded">
<?php echo '<h6 class="discussionname">' . $row2['first_name'] . ' ' . $row2['last_name'] . '</h6>';?>
</div>
</a>
<div class="col-xs-8 col-md-10 discussion_title">
<?php echo '<h5> '.$row2['discussion_title'].' -'. $row2['message_text'];?></h5>
<h6 class="pull-right">Dec. 25</h6>
</div>
</div>
<?php
};
You need logic to find the last message for each discussion. There is more than one way to write this condition.
The following does it using a not exists clause. This checks that there are no messages with a larger id for the discussion:
SELECT dm.discussion_id, up.first_name, up.last_name, dm.message_text, cd.discussion_title
FROM `user_profile` up INNER JOIN
discussion_messages dm
ON (user_profile.user_id = dm.user_id) INNER JOIN
case_discussion cd
ON (cd.discussion_id = dm.discussion_id)
WHERE dm.case_id = '$thecaseid' and
not exists (select 1
from discussion_messages dm2
where dm2.discussion_id = dm.discussion_id and
dm2.message_id > dm.message_id
)
ORDER BY dm.message_id DESC;
One suggestion, use table aliases. The amount of total code will be smaller and easier to understand. Use the limit clause to return 1 row.
$discussionquery = "
SELECT
m.discussion_id,
u.first_name,
u.last_name,
d.message_text,
c.discussion_title
FROM `user_profile` as u
INNER JOIN discussion_messages as m
ON (u.user_id = m.user_id)
INNER JOIN case_discussion c
ON (m.discussion_id = c.discussion_id)
WHERE
m.case_id = '$thecaseid'
ORDER BY
m.message_id DESC
LIMIT 1";

To display employee's leave which is same department

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>"

Taking values from a table and echoing them out

I am working on a messaging system for one of my sites and I'm having a lot of issues with getting the messages to show up. For some reason I can't get the syntax right so that it will take every single value that matches the receiver_id will display if the user_id matches the receiver_id. I had it working fine on my windows test machine, but when I uploaded it to my ubuntu server it broke. So now I'm trying to fix the code. What I have is this:
$m = "SELECT m.message_id, m.receiver_id, m.sender_id, m.subject, m.body, m.posted, u.id, u.username FROM messages m, users u WHERE u.id = {$_SESSION['id']}";
$b = mysqli_query($dbc, $m);
?>
<div class="mailbox">
Inbox<br />
Sent<br />
</div>
<div class="mailbox">
<h2>Messages for <?php echo $_SESSION['username']; ?></h2>
<?php echo output_message($message); ?>
<div id="messages">
<?php
if (mysqli_num_rows($b) > 0) {
while ($mess_row = mysqli_fetch_array($b, MYSQLI_NUM)) {
$u = "SELECT * FROM users WHERE id={$mess_row[1]}";
$rec = mysqli_query($dbc, $u);
$rec_row = mysqli_fetch_array($rec, MYSQLI_NUM);
$s = "SELECT * FROM users WHERE id={$mess_row[2]}";
$send = mysqli_query($dbc, $r);
$send_row = mysqli_fetch_array($send, MYSQLI_NUM);
echo "$mess_row[3] Posted by: <b>$send_row[1]</b> on: $mess_row[5]<br /><hr />";
}
} else {
echo "No messages.";
}
What am I doing wrong? I thought I had it fixed but then it just spit out the same record five times. I tried grouping which only gave me 1 record. I tried moving the $s call outside the while loop but I'm not able to draw on the sender's user_id that way. I just don't know what to do and I've searched all over for the past several hours and I can't find exactly what I'm looking for, or else I'm not typing the question right.
Thanks in advance.
Use a JOIN to get everything in one query:
$m = "SELECT m.message_id, m.receiver_id, m.sender_id, m.subject, m.body, m.posted, s.username sender_name, r.username receiver_name
FROM messages m
JOIN users r ON r.id = m.receiver_id
JOIN users s ON s.id = m.sender_id
WHERE u.id = {$_SESSION['id']}";
I apologize for hastily throwing this together. Hope it helps.
Use this as your query, then you won't have to go through and do that horrible extra set of queries to get the user info.
$id = $dbc->real_escape_string($_SESSION['id']);
$m = "SELECT m.message_id, m.receiver_id, m.sender_id, m.subject, m.body, m.posted, u.id, u.username
FROM messages m
INNER JOIN users u ON m.receiver_id=u.id
WHERE u.id = '$id';";
Extra note: Your need to escape your session id string. I'd probably also verify it is just numbers using a regex.
edit: Use #Barmar answers query in place of mine. I'd still add the escaping/regex though.

Categories