Left Join With Null value Table - php

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.

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

select from two mysql tables where column value is similar and id is retrieved from previous page

i have a question. my english isn't well. so i hope i explain well...
i have two tables, tbl_home and tbl_office, the question is
how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..
$a=$_POST['home_id']
the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form
<?php
$sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);
while($row = $result2->fetch_assoc()){
$a=$row['case_no'];
$bc=$row['colour'];
echo " $a <br/> ";
echo " $bc2 <br/>";
?>
is the select statement above correct??
soo, i just want anybody to take a look a this specific statement and how to make it right
$sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";
You need inner join to use:
" SELECT t_office.home_id,t_office.case_no,t_office.name FROM tbl_office
t_office INNER JOIN tbl_home t_home ON t_office.case_no = t_home.case_no;
where t_office.case_no ='$a'";
u can use "inner join" for example:
"SELECT t.home_id,t.case_no,t.name FROM tbl_office
t INNER JOIN tbl_home h ON h.case_no = h.case_no"
**select tbl_home.name,tbl_office.case_no,tbl_office.color from tbl_office
INNER JOIN tbl_home on tbl_office.case_no = tbl_home.case_no
where tbl_office.case_no ='$a';**
I hope this will be working fine until $a(case_no) value is existed in tbl_home or else it doesn't give any rows

How can I move records from a table to other table with selected field?

I need to move records to other table but I want a specific row or field like I want to move the student(table) records in the unvoted_logs but their are different field so I have to specific on inserting , I have a code but it doesn't work please I need help
$stud ="INSERT INTO unvoted_logs(idno,syearid)
SELECT idno,syearid FROM SELECT st.* FROM student st LEFT JOIN vote_logs sv ON st.idno = sv.idno AND st.syearid = sv.syearid
WHERE sv.idno IS NULL AND user_type='3'";
$qa = $db->prepare($stud);
Hi this is rough pseudocode from what I have done. By a brief explaination, I have separated the code you have provided into three steps.
Firstly SQL create a view from the inner select table.
Secondly SQL select a record from the view table
Thirdly SQL insertion by a separate query.
Hope it helps. Thanks.
$sql1 = "Create OR Replace View [student joins votes] AS
SELECT * FROM student st LEFT JOIN vote_logs sv
ON st.idno = sv.idno AND st.syearid = sv.syearid";
$qa = $db->prepare($sql1);
$qa->execute();
$sql2= "Select idno,syearid FROM [student joins votes] where WHERE idno IS NULL AND user_type='3'";
$qa = $db->query($sql2);
//only has one row in the database
if ($qa->num_rows == 1) {
// output data of each row
while($row = $qa->fetch_assoc()) {
$idno = $row["idno"];
$syearid = $row["syearid"];
break;
}
}
if($idno!=null && $syearid!=null){
$qa = $db->prepare("INSERT INTO unvoted_logs (idno, syearid)
VALUES (:idno, :syearid)");
$qa->bindParam(':idno', $idno);
$qa->bindParam(':syearid', $syearid);
$qa->execute();
}

How do I connect two tables to see if a value exist in any of the two

I having problems connecting the below query together so that It works more efficient.Can someone please tell me how I can connect these two queries so that it is only one?
$rs_duplicate = mysql_query("select count(*) as total
from advertisers_account
where user_email='$user_email' ") or die(mysql_error());
list($total) = mysql_fetch_row($rs_duplicate);
}
$rs_duplicate_pub = mysql_query("select count(*) as total
from publishers_account
where user_email='$user_email' ") or die(mysql_error());
list($totalpub) = mysql_fetch_row($rs_duplicate_pub);
if ($totalpub || $total > 0)
{
echo "Not Available ";
} else {
echo "Available";
}
Use a UNION:
SELECT 'advertisers' AS which, count(*) AS total
FROM advertisers_account
WHERE user_email = '$user_email'
UNION
SELECT 'publishers' AS which, count(*) AS total
FROM publishers_account
WHERE user_email = '$user_email'
This query will return two rows, you can use the which column to tell whether it's advertisers or publishers.
This is how you could do it. you need to use joins, but you should make sure to not let any variables in the query be directly from an outside user like from a form submit. That will open you up to SQL Injection. Use Prepared Statements instead.
select count(*) as total from publishers_account INNER JOIN advertisers_account ON advertisers_account.user_email = publishers_account.user_email WHERE user_email='$user_email'
in response to:
Can someone please tell me how I can connect these two queries so that it is only one?
Why not:
Select
(select count(*) as total from advertisers_account where user_email='$user_email') +
(select count(*) as total from publishers_account where user_email='$user_email') as sumofCount
SELECT count(advertisers_account.id)
FROM publishers_account
LEFT JOIN advertisers_account ON publisher_account.email = advertisers_account.email
WHERE publisher_account.email = '$user_email';
If the count is greater than zero, then the email exists in both tables at least once. If it exists only in the left table (publishers), then the counter would be zero. If it doesn't exist at all in the left table, then you'll get no rows at all, even if it does exist in the right table (advertisers)

Help construct a simple query Using 3 tables

Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1

Categories