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

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"

Related

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

For each SQL result, another SQL query? in PHP

I need help at getting data from MySQL Database. Right now I have a query that gives me:
Tournament ID
Tournament Name
Tournament Entry fee
Tournament Start and End date
For tournaments I am registered in. Now I want, for each tournament I am registered in, to count how many users are in that tournament, my points in that tournament, etc.
That info is in table called 'ladder'
ladder.id
ladder.points
ladder.userFK
ladder.tournamentFK
Database: http://prntscr.com/99fju1
PHP CODE for displaying tournaments I am registered in:
<?php
include('config.php');
$sql = "SELECT distinct tournaments.idtournament, tournaments.name, tournaments.entryfee, tournaments.start, tournaments.end
from tournaments join ladder
on tournaments.idtournament= ladder.tournamentFK and ladder.userFK=".$_SESSION['userid']."
group by tournaments.idtournament";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$tournament="<li class='registered' data-id=".$row['idtournament']." data-entryfee=".$row['entryfee']." data-prize=".$tournamentPrize."><span class='name'>".$row['name']."</span><span class='entry-fee'>Entry fee: ".$row['entryfee']."€</span><span class='prize-pool'>Prize pool: €</span><span class='date-end'>".$row['start']."-".$row['end']."</span><span class='btns'><button>Standings</button></span></li>";
echo $tournament;
}
}
$conn->close();
?>
Usually you can combine JOIN, COUNT() and GROUP BY in your query.
Some examples:
MySQL joins and COUNT(*) from another table
This would be the query I think.Change column and table name if its not correct. Not tested but I am sure this will give you some idea to make required query
select count(ladder.tournamentId)as userCount,tournaments.name
from
ladder left join tournaments
on ladder.tournamentId = tournaments.id
where ladder.tournamentId in
(
select tournaments.id from
tournaments left join ladder
on ladder.tournamentId = tournaments.id
where ladder.userId='yourId'
) and ladder.userId <> 'yourId'
group by ladder.tournamentId

Query from multiple MySQL tables using PHP

I have the following function which pulls in invoice data from tables invoices, however how can I get data from the customers table matching up invoice number:
So I guess need to get * from customers tables where invoice = invoice?
PHP
// the query
$query = "SELECT * FROM invoices ORDER BY invoice ASC";
// mysqli select query
$results = $mysqli->query($query);
// mysqli select query
if($results) {
print '<table class="table table-striped table-bordered" id="data-table" cellspacing="0"><thead><tr>
<th><h4>Invoice</h4></th>
<th><h4>Customer</h4></th>
<th><h4>Issue Date</h4></th>
<th><h4>Due Date</h4></th>
<th><h4>Status</h4></th>
<th><h4>Action</h4></th>
</tr></thead><tbody>';
while($row = $results->fetch_assoc()) {
print '
<tr>
<td>'.$row["invoice"].'</td>
<td>'.$row["customer_name"].'</td>
<td>'.$row["invoice_date"].'</td>
<td>'.$row["invoice_due_date"].'</td>
<td>test</td>
<td>Edit <a data-invoice-id="'.$row['invoice_id'].'" class="btn btn-danger delete-product">Delete</a></td>
</tr>
';
}
print '</tr></tbody></table>';
} else {
echo "<p>There are no invoices to display.</p>";
}
First of all, it's generally a better idea to include your keys in your select (and it's also easier to troubleshoot) instead of *. However, assuming that these are your fields, you can connect these using a JOIN like so:
SELECT *
FROM invoices i
JOIN customer c
ON c.invoice = i.invoice
ORDER BY i.invoice
Assuming you have a common key on each table, which as you suggest, is invoice (this is the huge advantage of using a database as opposed to a flat file), you can just join them together (the i and c are just shortcuts which make it easier to read the query).
You can also modify this with a WHERE after the ON row to narrow down your results, such as something like this (assuming you are looking for a specific invoice numbered 12345
SELECT *
FROM invoices i
JOIN customer c
ON c.invoice = i.invoice
WHERE i.invoice = 12345
ORDER BY i.invoice
SQL is pretty powerful. If you want to read up more, there are some great tutorials here on this site: http://www.w3schools.com/sql/
If you want to call this in your query (using the first example) you can just do it the same way you were, like so:
while($row = $results->fetch_assoc()) {
echo $row["invoice"];
}
Edit:
In the future it is better to declare your keys in the select. Assuming that customer_name is in the customer table, you would call it as c.customer_name in the select. However, here's how it would work with the wildcard to get everything from both tables. Change your query to this:
SELECT i.*, c.*
FROM invoices i
JOIN customer c
ON c.invoice = i.invoice
ORDER BY i.invoice
try this..
$query = "SELECT c.customer_name, i.* FROM invoices as i JOIN customers as c ON i.customer_id = c.id ORDER BY i.invoice ASC";
this will give you customer name as you require.
Refer to http://w3schools.com/sql/sql_join.asp
$query = "SELECT *
FROM Invoices I, Customers C
WHERE I.invoice = C.invoice
ORDER BY C.invoice ASC";
If you would prefer a statement without joins..

SQL select query to find count from given table

I have one table in database -> applicants_detail which has two column
applied_personid and applied_courseid.
College provides number of courses.
I have the given id to applied_courseid, that is written like this:
arts--1
science--2
maths--3...
And applied_personid which contains applied person id.
I need to count how many people applied for the course, like in the page it should show:
maths------15 people_applied
science------20 people_applied
I tried this query:
$query="select * from people where people_id in(select applied_personid from applicants where applied_courseid =".$_GET['postcourseid']." )";
And the code to find count is not able to show count in the table.
<?php
$count=0;
while($row=mysql_fetch_array($res))
{
echo '<tr> <td width="10%">'.$count.'
<td width="50%">'.$row['student_fnm'].'
<td width="50%">'.$row['applied_courseid'].'
<td width="30%">course name
';
$count++;
}
?>
You just need to group by applied_courseid. This should do it.
select applied_courseid, count(applied_personid) as `count`
from
applicants_detail
group by applied_courseid
Then if needed use the results here to join to the other tables
which you probably have (that would give the you course name e.g.).
Try this to get all data:
SELECT course_name, applied_courseid as course_id, count(applied_personid) as `student_number`
FROM applicants_detail
INNER JOIN course_detail ON course_detail.course_id = applicants_detail.course_id
GROUP BY applied_courseid

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

Categories