PHP - Getting wrong result when selecting from two tables - php

I have been trying to get some results when selecting combo boxes.
here is my query:
$strSQL = "SELECT * FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";
This query is returning all the studentresult.id = 2 where studentresult.id is primary.
This is the php code:
<td><div align="center"><?=$objResult["id"];?></div></td>
<td><div align="center"><?=$objResult["studentid"];?></div></td>
<td><?=$objResult["subjectid"];?></td>
<td><?=$objResult["marks"];?></td>
<td><div align="center"><?=$objResult["term"];?></div></td>
<td align="right"><?=$objResult["year"];?></td>
<td align="right"><?=$objResult["rank"];?></td>
The id is taken from student table rather than being taken from studentresult table. Can someone help me with this.
EDIT 1:
The id is present in both tables
EDIT 2:
Student result:
id| StudentID| SubjectID| Marks| Rank| Term| Year
Student:
id| Roll Num| class| Name| Surname
Thanking You In Advance
Bhaamb

$strSQL = "SELECT *,studentresult.id as stid FROM studentresult,student where studentresult.studentid=student.id and student.class='$classes' and term='$term'and studentresult.studentid=student.id and year='$year' ";
Then
<div align="center"><?=$objResult["stid"];?></div>

You Better specify the column names instead of (*) from both the tables alias the column names to avoid column name conflicts if both are same and also try to use Join(Inner or Left) based on the need.
for example, some thing like this:
SELECT S.id AS student_id, SR.id as StudentResultId, S.class, s.year
FROM studentresult AS SR
INNER JOIN student AS S
WHERE SR.studentid=S.id and S.class='$classes' and s.term='$term'and SR.studentid=s.id and s.year='$year'

First of all, why do you use this twice in the where clause?
studentresult.studentid=student.id
Please define all needed columns explicitly while joining tables having the same column names, e.g.
SELECT studentresult.id as sr_id, student.id as s_id ... FROM ...
and change it in your php code:
<?=$objResult["sr_id"];?>

Related

mysql - group results by id and print

I have "reservation" table (mySql) that contain number of columns: res_id, hotel_id, hotel_name, from_date, to_date.
I would like to select and print html table for each hotel (i'm using PHP). the result should be a title - the name of the hotel, and bellow it a list of reservation for the specific hotel.
I can do GROUP BY:
Select * FROM reservation GROUP BY hotel_id
I'm not sure if it's the right way to do it, and how do i print the results without checking all the time if the hotel_id was changed?
Thank you in advanced
GROUP BY is definitely NOT the right way to approach this. One method would be:
SELECT *
FROM reservation
ORDER BY hotel_id;
You would then loop through the result sets. When the hotel name changes, you would put in the title of the hotel.
Note: This is a poor data model if it has both the hotel id and name in reservation. This would normally be in hotel and you would connect the tables using JOIN:
SELECT h.hotel_name, r.*
FROM hotels h JOIN
reservation r
ON r.hotel_id = h.hotel_id
ORDER BY hotel_id;
Using a LEFT JOIN, you can even get hotels with no reservations.
How is it that the hotel_id would change? As per your question it seems that hotel_id is a column made for join with a "hotels" table, isn't it?
Regarding the "group by", why would you group by hotel? This would make you loose reservations data, unless you were using some sort of group_concat.
If you want to get the reservations from a specific hotel you could loop through your hotels table and inside your loop you can do:
SELECT * FROM reservations WHERE hotel_id='QUERIED_HOTEL_ID'
Then show the results.
Or you could simply
SELECT * FROM reservations
And when you get the fetched results you can make a multidimensional php array with 'hotel_id' as top level key and 'res_id' as secondary, like this:
$reservations_by_hotel = [];
do {
$resId = $row['res_id'];
$hotelId = $row['hotel_id'];
$reservations_by_hotel[$hotelId][$resId] = $row;
} while ($row = $result->fetch_assoc());

Update value from one database to another database - fastest method

I have two tables.
first datatable structure has nine columns but the important three are:
code | name | value
2D3 | name test | 0.12
the second table has the same three columns.
Now I want to update all rows of the first table with the values of table two where code AND name are the same as in table two.
So my current idea is to do a select of all rows of table 1 with the code and name columns, than check if a row with the same code and name exists in table 2, if yes get that value and do a UPDATE query in table 1 with value of table 2.
The problem is that the two tables are hugh and I am sure that I am not using the fastest method.
anyone an idea for the fastest method to do this? Thank you very much!
EDIT: the query:
$getall = "SELECT code, name, value FROM table2";
$query = mysqli_query($conn, $getall );
while($result = mysqli_fetch_array($query))
{
$UpdateAll = "UPDATE table1 SET value = '".mysqli_real_escape_string($conn,$result["value"])."' WHERE name = '".mysqli_real_escape_string($conn,$result["name"])."' AND code = '".mysqli_real_escape_string($conn,$result["code"])."'";
$result2 = mysqli_query($conn, $UpdateAll); }
You speak of two databases but really mean two tables, don't you? In this case, you can do it with one update using a join, like this:
update table1 t1
inner join table2 t2 on t2.code = t1.code and t2.name = t1.name
set t1.value = t2.value;

Multiple PHP subqueries not giving desired result

I have a MySQL table from which I want to extract attendance information(Student Id, course/subject for attendance, date range,whether the student was present or not). I have written the following query:
SELECT
COUNT(a_id),
(
SELECT COUNT(*) FROM attendance
WHERE state = 'present'
AND `dater` BETWEEN '$a' AND '$b'
) AS Count,
stud_id
FROM attendance
WHERE
stud_id =(SELECT id FROM users WHERE NAME = '$stud')
Which is giving me the correct results, but when I change the student,its not giving me the correct count for the days recorded for present. Not mention that I have not yet added the course parameter into the query
The MySQL table is as follows:
I need help for the query to return the desired results(Count the accurate days present for each student, as well as adding the course parameter into the query so that the query will look for attendance records for a specific course, for a specific student, for a specified date range).
Looks like you want to seperate your queries:
Select (select count(*) from <database>.attendance where state = 'present' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as present, (select count(*) from <database>.attendance where state = 'absent' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as absent from <database>.attendance WHERE stud_id =(SELECT id FROM users WHERE NAME = '$stud');
try this :)
Resolved it using JOIN as follows:
SELECT u.id, a.stud_id, a.course_id, count(*) FROM attendance a
JOIN users u ON u.id=a.stud_id
JOIN courses c ON c.c_id=a.course_id
WHERE a.state='present' and dater between '2017-09-01' and '2017-09-14'
GROUP BY a.stud_id, a.course_id;
Thanks for your help.

Joining two tables

I am trying to join a dataofbirth column which is in studentdetails table with another table called college table, I need the dataofbirth of the student in the second table.Here is my query.
$result = mysqli_query($con,"SELECT `DateofBirth` FROM `studentdetails` INNER JOIN `college`
ON `studentdetails`.StudentID = college.StudentID")or die ("Error: ".mysqli_error($con)");
So when I fetch my array for the second table I would be able to get their dataofBirth of student without joining them physically.
Can anyone spot what's wrong with my syntax ?
Thank you
If you want to join two tables you have to provide the list of columns from both tables that you want to be included in joined/combined table. So:
Try this (substituting [add other columns..] bit with the other columns you might want to include. And take note of the table aliases how they are being used:
$result = mysqli_query($con,"SELECT s.DateofBirth, c.StudentID, [add other columns from college table here...] FROM studentdetails sd INNER JOIN college c
ON sd.StudentID = c.StudentID")or die ("Error: ".mysqli_error($con)");
oh and you might want to use mysqli instead of old, deprecated, ugly, slow, insecure, suicidal thoughts inducing mysql_ extension ;)
It should be (from the comment : dateofbirth only exists in the studentdetails )
$result = mysqli_query($con,"SELECT sd.DateofBirth FROM studentdetails as sd INNER JOIN college as c
ON sd.StudentID = c.StudentID")or die ("Error: ".mysqli_error($con)");
Considering that we born only once (except for phoenixes) the relationship between students and their date of birth is supposed to be 1:1 relationship. In other words, column DateOfBirth could be declared in college table. Then to select their date of birth you simple could do:
select DateOfBirth
from college
where StudentID = :id
But I see you already have another table to store their date of birth so you could do a join to select their date of birth:
select d.DateOfBirth
from college c,
studentdetails d
where c.StudentID = d.StudentID;
Or:
select d.DateofBirth
from studentdetails d
inner join college as c
on d.StudentID = c.StudentID;
But this queries above would exclude the students without records in studentdetails from your result. To select all students with their respective date of birth you could do:
select c.StudentID,
s.DateOfBirth
from studentdetails d
right join college c
on d.StudentID = c.StudentID;
This right join query gets all the students even if they don't have a date of birth in studentdetails table (right join cmd on table college).
You're free to figure out what's the best alternative to you, but I recommend you to normalize this data model putting column DateOfBirth inside college table.

Converting two loops to smarty

I have two cycles in PHP, that I needed converting to smarty structure. Down includes PHP code.
Code:
<pre>
$query = mysqli_query($cnn, "SELECT *, COUNT(*) AS ph FROM course INNER JOIN completed_course ON course.id = completed_course.id_course GROUP BY course.id");
while ($row = mysqli_fetch_array($query)){
<tr> <td> <?php echo $row['id']; ?></td><td> <?php echo $row['nazev']; ? </td><td>
?php echo $row['ph']; ? </td> <td>
?php
$Number_of_graduates = mysqli_query($cnn, "SELECT COUNT(*) AS abs FROM participant where id_completed_course = $row[id]");
while ($rAbs = mysqli_fetch_array($Number_of_graduates)){
echo $rAbs['abs'];
} ?
</td>
</pre>
The question is. How to convert the second loop where first id from SQL?
Ok, so your question is really about SQL. Let's look at your queries. The first one looks like this:
SELECT *, COUNT(*) AS ph
FROM course
INNER JOIN completed_course ON course.id = completed_course.id_kurz
GROUP BY course.id
I'm assuming (because I don't know anything about your database scheme) that this is going to give a list of courses and the number of students (maybe - I don't know what's in the completed_course table) who completed them. As written, this query is going to also give you some data from the completed_course table, but it's likely to be meaningless since you're grouping only on course.id.
The second query is:
SELECT COUNT(*) AS abs
FROM participant
WHERE id_completed_course = {DATA FROM FIRST QUERY}
Presumably, this query is intended to give you the total number of participants of completed courses. To make that work, the WHERE clause could look like this:
SELECT COUNT(*) AS abs
FROM participant
WHERE id_completed_course IN (
SELECT course.id FROM
FROM course
INNER JOIN completed_course ON course.id = completed_course.id_kurz
)
Notice that I'm taking the values selected in the first query and making them part of an IN clause. This query can be simplified significantly - for instance, the JOIN in the subquery is really only selected ID values from the completed_course table:
SELECT COUNT(*) AS abs
FROM participant
WHERE id_completed_course IN (
SELECT id_kurz
FROM completed_course
)
And the query will actually be more efficient if you get rid of the subquery altogether and just join the participants to the completed_course table.
SELECT COUNT(*) AS abs
FROM participant
INNER JOIN completed_course ON participant.id_completed_course=completed_course.id_kurz
This last query is going to give you one value: the number of participants whose id_completed_course value corresponds to an item in the completed_course table. You can use the mysqli methods to retrieve this data and pass it to your Smarty template.

Categories