Query from multiple MySQL tables using PHP - 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..

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

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

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

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"

MySQL: Multiple Photos and Videos for News with Joins

I want multiple photos and multiple videos, the main problem is that I can't get them inline if I don't use joins.
So for example, I get 2 photos a video and again a photo.
I have a parent news table and 2 secondary table news_photos and news_videos and I want to get in one query the photos and videos for the news.
Is this somehow possible?
mysql_query("
SELECT *
FROM news_photos, news_videos
FULL JOIN news_videos
ON news_id = {$news_id}
FULL JOIN news_photos
ON news_id = {$news_id}
");
An image about the structure:
There's actually only a single FULL JOIN in that, since you are not involving the news table at all.
SELECT *
FROM news_photos
FULL JOIN news_videos
ON news_photos.news_id=news_videos.news_id
WHERE news_photos.news_id=... OR news_videos.news_id=...
FULL JOIN is not supported by MySQL. It can be less-efficiently simulated using two LEFT JOINs and a UNION, but it's relatively rare that you actually need to. Assuming every photo and video does belong to a news, you could avoid it and get a more conventional query by bringing the news table into it:
SELECT *
FROM news
LEFT JOIN news_photos ON news_photos.news_id=news.id
LEFT JOIN news_videos ON news_videos.news_id=news.id
WHERE news_id=...
But still, this is almost certainly not what you mean! If there are multiple photos and videos for a news item, you would be effectively creating a cartesian product, where every combination of photo and video produces a row. This is the sort of combinatorial explosion you almost never want!
If you just want one of each photo and video, I suppose you could hack that into a single query using a LEFT JOIN that will always give NULL on the other side:
SELECT * FROM news_photos
LEFT JOIN news_videos ON 0
WHERE news_photos.news_id=...
UNION SELECT * FROM news_photos
RIGHT JOIN news_videos ON 0
WHERE news_videos.news_id=...
But there's really nothing to be gained by this. Don't shoehorn two separate queries (“I'd like the photos for a news, and the videos for a news”) into one. Just do it the trivial way:
SELECT * FROM news_photos
WHERE news_id=...
SELECT * FROM news_videos
WHERE news_id=...
i would do it using a stored procedure that had multiple select statements as follows:
http://pastie.org/1141100
drop procedure if exists list_news_photos_videos;
delimiter #
create procedure list_news_photos_videos
(
in p_news_id int unsigned
)
proc_main:begin
select n.* from news n where n.news_id = p_news_id;
select p.* from news_photos p where p.news_id = p_news_id order by photo_id desc;
select v.* from news_videos v where v.news_id = p_news_id order by video_id desc;
end proc_main #
you would call this in mysql as follows:
call list_news_photos_videos(2);
then you can call the stored procedure from php (1 db call only) using mysqli as follows:
http://pastie.org/1141103
<?php
// quick and dirty demo - needs to be made more robust !!
$db = new Mysqli("localhost", "foo_dbo", "pass", "foo_db");
$sql = sprintf("call list_news_photos_videos(%d)", 2); // get all the news related data in one query
$result = $db->query($sql);
//news item
$row = $result->fetch_assoc();
echo sprintf("<h2>news item</h2>news_id = %d subject = %s <br/>", $row["news_id"], $row["subject"]);
$result->free();
//news photos
$db->next_result();
$result = $db->use_result();
echo "<h2>news photos</h2>";
while ($row = $result->fetch_assoc()){
echo sprintf("photo_id = %d subject = %s<br/>", $row["photo_id"], $row["subject"]);
}
$result->free();
//news videos
$db->next_result();
$result = $db->use_result();
echo "<h2>news videos</h2>";
while ($row = $result->fetch_assoc()){
echo sprintf("video_id = %d subject = %s<br/>", $row["video_id"], $row["subject"]);
}
$result->free();
$db->close();
?>

Categories