To display employee's leave which is same department - php

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

Related

Echo contents of JOIN SQL tables with MySQLi

I'm working on a system, and this module is supposed to echo the contents of the database.
It worked perfectly until I added some JOIN statements to it.
I've checked and tested the SQL code, and it works perfectly. What's not working is that part where I echo the content of the JOINed table.
My code looks like this:
$query = "SELECT reg_students.*, courses.*
FROM reg_students
JOIN courses ON reg_students.course_id = courses.course_id
WHERE reg_students.user_id = '".$user_id."'";
$result = mysqli_query($conn, $query);
if (mysqli_fetch_array($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo $row["course_name"];
echo $row["course_id"];
The course_name and course_id neither echo nor give any error messages.
UPDATE: I actually need to increase the query complexity by JOINing more tables and changing the selected columns. I need to JOIN these tables:
tutors which has columns: tutor_id, t_fname, t_othernames, email, phone number
faculty which has columns: faculty_id, faculty_name, faculty_code
courses which has columns: course_id, course_code, course_name, tutor_id, faculty_id
I want to JOIN these tables to the reg_students table in my original query so that I can filter by $user_id and I want to display: course_name, t_fname, t_othernames, email, faculty_name
I can't imagine that the user_info table is of any benefit to JOIN in, so I'm removing it as a reasonable guess. I am also assuming that your desired columns are all coming from the courses table, so I am nominating the table name with the column names in the SELECT.
For reader clarity, I like to use INNER JOIN instead of JOIN. (they are the same beast)
Casting $user_id as an integer is just a best practices that I am throwing in, just in case that variable is being fed by user-supplied/untrusted input.
You count the number of rows in the result set with mysqli_num_rows().
If you only want to access the result set data using the associative keys, generate a result set with mysqli_fetch_assoc().
When writing a query with JOINs it is often helpful to declare aliases for each table. This largely reduces code bloat and reader-strain.
Untested Code:
$query = "SELECT c.course_name, t.t_fname, t.t_othernames, t.email, f.faculty_name
FROM reg_students r
INNER JOIN courses c ON r.course_id = c.course_id
INNER JOIN faculty f ON c.faculty_id = f.faculty_id
INNER JOIN tutors t ON c.tutor_id = t.tutor_id
WHERE r.user_id = " . (int)$user_id;
if (!$result = mysqli_query($conn, $query)) {
echo "Syntax Error";
} elseif (!mysqli_num_rows($result)) {
echo "No Qualifying Rows";
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row["course_name"]}<br>";
echo "{$row["t_fname"]}<br>";
echo "{$row["t_othernames"]}<br>";
echo "{$row["email"]}<br>";
echo "{$row["faculty_name"]}<br><br>";
}
}

Left Join With Null value Table

I was using this query to connect my student table and attendance table,
My Problem is, sometimes, attendance table has no value.
It's not returning any value.
<?php
if($_SERVER['REQUEST_METHOD']=="POST"){
include('include/connection.php');
showData();
}
function showData(){
global $connect;
$teacher_id = $_POST['teacher_id'];
$subject_id = $_POST['subject_id'];
$date = $_POST['date'];
$query ="
SELECT s.student_name
, s.student_number
, s.student_section
, s.subject_id
, s.fingerprint_id
, s.teacher_id
, a.status
FROM tbl_student s
LEFT
JOIN tbl_attendance a
on s.subject_id=a.subject_id
WHERE s.subject_id = '$subject_id'
and a.date='$date'
and s.teacher_id = '$teacher_id';";
$result =mysqli_query($connect,$query);
$number_of_rows = mysqli_num_rows($result);
$temp_array=array();
if($number_of_rows>0){
while($row=mysqli_fetch_assoc($result)){
$temp_array[]=$row;
}
}
header('Content-Type: application/json');
echo json_encode(array("student"=>$temp_array));
mysqli_close($connect);
}
?>
What I want to achive is even if attendance table has no value,
I can still see the student fields.
Is it even possible with SQL query? Thanks
You have to move the fields of table attendance from where to the on condition:
$query ="SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
FROM tbl_student student
LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date'
WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';";
Because first the join Statement will be executed and then the where, if you access the table tbl_attendance in where ans all the columns are null, they will filtered out.
Hint: read about prepared Statements to provide SQL-injection
SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status
FROM tbl_student student
LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date'
WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';
Try above code.Hope this will helps.
As you had made condition on student table using attendance.date='$date' on WHERE clause it exclude that record which are not satisfy this condition.
So instead of where i had put that condition through ON clause on LEFT JOIN.
This will achieve your goal.

Why does one of my column shows empty?

I have my table that one of my column shows empty. It has the column of Id, Date, Cust name, Product + Qty, and amount. But only in Product + Qty shows empty even it has data in database.
PHP code
<?php
include('connect.php');
$start = isset($_GET['d1']) ? $_GET['d1'] : '';
$end = isset($_GET['d2']) ? $_GET['d2'] : '';
if(isset($_GET['submit']) && $_GET['submit']=='Search')
{
$result = mysql_query(
"SELECT
t1.qty,
t2.lastname,
t2.firstname,
t2.date,
t3.name,
t2.reservation_id,
t2.payable FROM prodinventory AS t1
INNER JOIN reservation AS t2
ON t1.confirmation=t2.confirmation
INNER JOIN products AS t3
ON t1.room=t3.id
WHERE str_to_date(t2.date, '%d/%m/%Y') BETWEEN
str_to_date('$start', '%d/%m/%Y') AND
str_to_date('$end', '%d/%m/%Y')
GROUP BY t2.confirmation") or die(mysql_error());
while ($row = mysql_fetch_array($result)){
echo'<tr class="record">';
echo '<td>'.$row['reservation_id'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>';
echo '<td><div align="left">';
$rrr=$row['confirmation'];
$results = mysql_query("SELECT * FROM prodinventory where confirmation='$rrr'");
while($row1 = mysql_fetch_array($results))
{
$roomid=$row1['room'];
$resulta = mysql_query("SELECT * FROM products where id='$roomid'");
while($rowa = mysql_fetch_array($resulta))
{
echo $rowa['name'].' x';
}
echo ' '.$row1['qty'].'<br>';
}
echo '<td>'.'PHP ' . number_format(floatval($row['payable']));
}
?>
Hmmmm I have deleted my answer but noone tried so...
I think this echo ' '.$row1['qty'].'<br>'; is the row you asked about. And all this looks like a typo. If this is the case:
You have no confirmation in the SELECT clause (it's used only in JOIN and GROUP BY) and it possible your $rrr to be blank. Echo it to be sure there is a value.
Check does your query works and return results. Echo the query string (or take it from the mysql log file) and test it.
You have SELECT *. Is the field name 'qty' correct in a case-sensivity environment? 'Qty' may be different and the query may work but you don't get the result.
i think that's because you have inner join and maybe the intersection tables have no data
try to do left join first if it works
insure that all of tables have data in it

how to select data from 2 table of databace in mysql....?

I have 2 table of date , student_info and student_payment in my databace...
in student_info i have:
id, student_id,student_mail,student_pass,student_name,...
and in student_payment have:
id,student_id,student_payment_id,student_payment_date,...
so my problem is here, i wanna select student_name where student_id form student_info but i have problem and mysql give my an error:
$db->connect();
$sql = "SELECT * FROM `student_payment`";
$rows = $db->fetch_all_array($sql);
$student_id = $rows['student_id'];
$sql2 = "SELECT * FROM `student_info` WHERE student_id=$student_id";
$rows2 = $db->fetch_all_array($sql2);
$db->close();
foreach($rows as $record ){
// i wanna to use student_name in first line
echo "\n<tr>
<td>$record[student_id]</td>
<td dir=\"ltr\">$record[student_payment]</td>
<td dir=\"ltr\">$record[student_payment_id]</td>
<td dir=\"ltr\">$record[student_payment_bank]</td>
<td dir=\"ltr\">$record[student_payment_type]</td>
<td dir=\"ltr\">$record[student_payment_date]</td>
<td dir=\"ltr\"></td>
</tr>\n";
}
but i dont know how to connect student_id and student_name and use in foreach because i have 2 rows of data.
(i'm a beginner in PHP / MySql)
Instead of querying database twice, you can instead join the tables to get the rows you want. Try to execute the query below in PhpMyAdmin or directly on MySQL Browser.
SELECT a.*, b.*
FROM student_info a
INNER JOIN student_payment b
ON a.student_ID = b.student_ID
-- WHERE ...if you have extra conditions...
ORDER BY b.student_payment_date DESC
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
It is possible to fix it with INNER JOIN, you can join 2 tables and use both values from 1 query.
http://www.w3schools.com/sql/sql_join_inner.asp
Or you can use the OOP way, not sure if that is what you need.
Make 2 objects from the 2 query's and put them in a foreach.
try this
$sql2 = " SELECT * FROM `student_info` WHERE student_id= '$student_id' ";
try this
$sql2 = "SELECT * FROM `student_info` WHERE student_id IN ($student_id)";
foreach($rows as $record ){
// i wanna to use student_name in first line
echo "\n<tr>
<td>$record[student_id]</td>
<td dir=\"ltr\">".$record['student_payment']."</td>
<td dir=\"ltr\">".$record['student_payment_id']."</td>
<td dir=\"ltr\">".$record['student_payment_bank']."</td>
<td dir=\"ltr\">".$record['student_payment_type']."</td>
<td dir=\"ltr\">".$record['student_payment_date']."</td>
<td dir=\"ltr\"></td>
</tr>\n";
}
Use Mahmoud Gamal code
But always select the needed columns only not all because
In future number of columns in table may increase which may decrease the performance of your application.
Also it may contain some important information not to be leaked.
It seems like you want a report of all payments made. The student name is to be displayed with the payment information. The results will probably have more than one payment per student.
This result is ordered by student name, and then payment date (most recent first)
SELECT s.student_name, sp.*
FROM student_payment sp
INNER JOIN student_info s ON s.student_ID=sp.student_ID
ORDER BY s.student_name ASC, sp.student_payment_date DESC
try to join the table and use single query instead of two -
$sql = "SELECT * FROM student_info, student_payment
WHERE student_info.student_id=student_payment.student_id"

SQL ERROR When i join 2 tables

Sorry let me revise. I have a three tables:
events_year
• EventID
• YearID
• id
Date
• YearID
• Year
Event
• EventID
• EventName
• EventType
i want to dispay a record from the three tables like so:
EventName - Year: Marathon - 2008
i linked it to a table called "members" which contains a ID number field (members-id)
so i can limit the results to members id = $un(which is a username from a session)
I need to join the three tables and limit the results to the specific ID number record
Here is my portion of the code:
$query = "SELECT * FROM members JOIN events_year ON members.id = events_year.id ";
"SELECT * FROM Event JOIN events_year ON Event.EventID = events_year.EventID WHERE username = '$un'";
"SELECT * FROM Date JOIN events_year ON Date.YearID = events_year.YearID WHERE username = '$un'";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo $row['Year'];
echo " - ";
echo $row['Event'];
echo "<br>";
}
the notices are almost self-explaining. There are no 'Year' and 'EventName' fields in the resultset. It's difficult (or: impossible) to tell why this happens as you haven't given your table-structure, but i guess this: 'Year' is a field of the date-table, 'EventName' is a field of the event-table - you're only selecting from members so this fields don't occur.
I don't understand why there are three sql-statements but only one is assigned to a variable - the other two are just standing there and do nothing. Please explain this and put more information into your question about what you're trying to achive, what your table-structure looks like and whats your expected result.
I think what you really wanted to do is some kind of joined query, so please take a look at the documentation to see how this works.
finally, i think your query should look like this:
SELECT
*
FROM
members
INNER JOIN
events_year ON members.id = events_year.id
INNER JOIN
Event ON Event.EventID = events_year.EventID
INNER JOIN
´Date´ ON ´Date´.YearID = events_year.YearID
WHERE
members.username = '$un'
Does the field 'Year' exist in the query output ? I suspect not.
the string $query is only using the first line of text:
"SELECT * FROM members JOIN events_year ON members.id = events_year.id ";
and not the others.
The query itself is not returning any fields that are called Year or EventName.
Do a var_dump($row) to find out what is being returned.

Categories