Using JOIN to display data in a table - php

Thanks for reading my question
i am trying to make *clients_id* from the table repair_jobs appear as the name from the table contacts
but i am having no luck
i have got 2 sql query's is this wrong?
the 1st
$query = "select * from repair_jobs";
this helps me display the information i need regarding the fields from repair_jobs and works
this is the 2nd
$query = "SELECT repair_jobs.client_id, contacts.name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.name";
under that i have this to try to display the name of the client
echo "<td>{$client_id}</td>";
but it is only displaying the number and not the data (clients name) that i need
am i missing something?
Additional information
The client_id (repair_jobs) is a number and is the same as id (contacts) but wanting to display the name (contacts)
CLIENTS
Id – name – surname – phone – address
REPAIRS
Id – clients_id (same as id in clients) – unit – date – price
current code
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = "select * from repair_jobs";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record
//start table
//creating our table heading
echo " <table class='table_basic'>";
echo "<thead><tr>";
echo "<th>Job #</th>";
echo "<th>Name Of Unit</th>";
echo "<th>Client</th>";
echo "<th>Estimated Value</th>";
echo "</thead></tr><tbody><tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td width='40px'><a href='rdetails.php?id={$id}'># {$id}</a></td>";
echo "<td>{$rmake} {$rmodel}</td>";
$query = "SELECT rj.client_id, c.name AS client_name FROM repair_jobs rj INNER JOIN contacts c ON rj.client_id=c.id";
echo "<td>{$client_name}</td>";
echo '<td align="center"><span class="badge badge-success">£';
$lhours = $labour;
$repaircosts = $ourcosts;
$labourpay = $labourcharge;
$sum_total = $repaircosts +($lhours * $labourpay);
print ($sum_total);
echo '</span></td>';
echo "</td>";
echo "";
}
echo "</tr></table>";//end table
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>

Change your 1st query to you join query, as there is no reason to do a 2nd query in the middle of your code. (also you never executed that query anyway).
//query all records from the database
$query = "SELECT repair_jobs.*, contacts.name as client_name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.id";
Then in your table keep the $client_name
echo "<td>{$client_name}</td>";

<?php
include 'db_connect.php';
$query = "SELECT rj.Id AS job_number, rj.unit, rj.make, rj.model, c.name AS client_name, rj.price FROM repair_jobs rj INNER JOIN contacts c ON rj.clients_id = c.id ORDER BY c.date";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
if( $num_results > 0){ //it means there's already a database record
echo " <table class='table_basic'>";
echo "<thead><tr>";
echo "<th>Job #</th>";
echo "<th>Name Of Unit</th>";
echo "<th>Client</th>";
echo "<th>Estimated Value</th>";
echo "</tr></thead><tbody>";
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<tr>";
echo "<td width='40px'><a href='rdetails.php?id={$job_number}'>#{$job_number}</a></td>";
echo "<td>{$make} {$model}</td>";
echo "<td>{$client_name}</td>";
echo "<td align='center'><span class='badge badge-success'>£";
$lhours = $labour;
$repaircosts = $ourcosts;
$labourpay = $labourcharge;
$sum_total = $repaircosts +($lhours * $labourpay);
echo $sum_total;
echo '</span></td>';
echo "</td>";
echo "</tr>";
}
echo "</tbody></table>";
} else {
echo "No records found.";
}
$result->free();
$mysqli->close();
?>

Related

Joining three tables and displaying value using php

I have used join and was able to get output table in phpmyadmin using this query :
$query = "SELECT members.usn, members.name, events.ename FROM members JOIN participant ON members.usn = participant.usn JOIN events ON events.eid = participant.eid WHERE members.usn='.$usn.'";
$result = $conn->query($query);
The Output was
usn
name
ename
7DC18CS005
John
Robo Wars
I used PHP to display this in my homepage for specific user by maintaining usn in their SESSION.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>';
echo $row[0];
echo '</td>';
echo '<td>';
echo $row[1];
echo '</td>';
echo '<td>';
echo $row[2];
echo '</td>';
echo '</tr>';
}
} else {
echo "No Members[Connected DB]";
}
But the output gives me
"No Members[Connected DB]"
instead of expected output which is
usn
name
ename
7DC18CS005
John
Robo Wars
Thank you!
You have a typo in the query. Looks like you are trying to concatenate $usn to the query but you got it wrong.
Change
$query = "SELECT members.usn, members.name, events.ename FROM members JOIN participant ON members.usn = participant.usn JOIN events ON events.eid = participant.eid WHERE members.usn='.$usn.'";
To
$query = "SELECT members.usn, members.name, events.ename FROM members JOIN participant ON members.usn = participant.usn JOIN events ON events.eid = participant.eid WHERE members.usn='$usn'";

Echo two SQL queries in one HTML table

I'm trying to display information from two queries in one single table, but can't figure out how to make it work.
This is what I got working with one query:
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
Company Employees
ABC 45
DEF 15
GHI 5
Now beneath that I'd like to have another query that simply counts all rows, giving me the total amount of Employees.
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
SELECT COUNT(*) AS Total FROM Employee_Table;
Company Employees
ABC 40
DEF 15
GHI 5
Total 60
This is what my code looks like right now. I defined two extra variables for my extra query that I want to echo out, but believe this is not the proper way to do it as I get an sqlsrv_fetch_array error.
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1, $result2)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo $row["Total"];
echo "</td></tr>";
}
echo "</table>";
How can this be achieved? I'd appreciate any help
First correct
sqlsrv_fetch_array()
see here http://php.net/manual/de/function.sqlsrv-fetch-array.php
Use just a single query and use mysqli_num_rows() function to count
$count = mysqli_num_rows($result);
I think you can achieve this by using only first query
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$result1 = mysql_query($conn, $query1);
$total_employee = 0;
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=mysql_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
$total_employee += $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
echo "<tr><td>Total</td><td>$total_employee</td></tr>";
echo "</table>";
You can use only one query:
$result = sqlsrv_query($conn, "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC");
?>
<table id='total'>
<tr><th>Company</th><th>Amount of employees</th></tr>
<?php
$total = 0;
while ($row=sqlsrv_fetch_array($result)) {
$total += $row["count"];
?>
<tr><td><?= $row["Company"] ?></td><td><?= $row["count"] ?></td></tr>
<?php
}
?>
<tr><td></td><td><?= $total ?></td></tr>
</table>
<?php
Try the following code
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
$rows = sqlsrv_fetch_array($result1)
echo "<tr><td>";
echo $rows["Total"];
echo "</td></tr>";
echo "</table>";

Sum Columns in PHP table

I have an index.php with various SQL queries which helps me find the balances of the respective accounts. This is a TRIAL BALANCE so I need to SUM all the amount in the Debit Column and SUM all the amount in the Credit Column so that I can Tally both of them. Please help me with the SUM. All values are echoed to a PHP table.
index.php
<?php
echo "<table border='1'>";
echo "<tr><th width='150'>Account</th><th width='200'>Debit</th><th width='200'>Credit</th></tr>";
echo "<tr><th align='left'>Cash & Bank</th></tr>";
//List the Banks first with their respective balances.
$bank_sql = "SELECT * FROM bank";
$bank_query = mysqli_query($conn, $bank_sql);
while ($bank_result = mysqli_fetch_array($bank_query)){
$bank_name = $bank_result['name'];
$sql= "SELECT SUM(amount) FROM account WHERE (mode='$bank_name' AND status='completed') AND (type='p' OR type='r')";
$sql_query = mysqli_query($conn, $sql);
while($sql_result = mysqli_fetch_array($sql_query)){
$sql_value = $sql_result['SUM(amount)'];
}
$sql1 = "SELECT SUM(amount) FROM account WHERE (mode='$bank_name' AND status='completed') AND (type='s' OR type='pa')";
$sql1_query = mysqli_query($conn, $sql1);
while($sql1_result = mysqli_fetch_array($sql1_query)){
$sql1_value = $sql1_result['SUM(amount)'];
}
echo "<tr><td>".$bank_name."</td>";
if ($sql_value > $sql1_value){
echo "<td align='right'>AED " . number_format(($sql_value - $sql1_value),2) . "</td><td>&nbsp</td>";
}
elseif ($sql1_value > $sql_value) {
echo "<td>&nbsp</td><td align='right'>AED " . number_format(($sql1_value - $sql_value),2) . "</td>";
}
else {
echo "<td>&nbsp</td><td>&nbsp</td>";
}
}
echo "</tr></table>";
}
?>
Try the below query
SELECT SUM(amount) FROM ht_account WHERE mode='$bank_name' AND status='completed' AND type IN('sale','purchase','reciept','payment')
A quick way to do it would be.
$sql3="select column1,column2 from yourtable where ..condition";
$sumofcolumn1;
$sumofcolumn2;
while($sql3_result = mysqli_fetch_array($sql3))
{
$sumofcolumn2+=$sql3_result['column2'];
$sumofcolumn1+=$sql3_result['column1'];
}
echo $sumofcolumn1.' '.$sumofcolumn2

Why Isn't My Data Being Shown?

I have the following tables in my database:
Minutes: minute_id, subject, next_subject, approval, meeting_id
Agendas: agenda_id, subject, duration, approval, reason, meeting_id
I am using the following PHP code:
<?php
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Minutes ON Minutes.meeting_id = Agendas.meeting_id WHERE Agendas.Approval = 'disapproved'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'You Have No New Messages';
} else {
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><br/>" .'Title: '. $info['title']." </td>";
echo "<td><br/>" .'Approved?: '. $info['approval']. "</td>";
echo "<td><br/>" .'Reason: '. $info['reason']."</td>";
echo "<hr>";
}
}
echo "</tr>";
echo "</table>";
?>
I am not getting the desired data to be shown as I am only been presented with the message 'You Have No New Messages' when in the agendas table, there is a row which has a field disapproved!
Any ideas?
You are doing an INNER JOIN... make sure there is also an associated row in the minutes table, or else there will be no data to return, even if there is an entry in Agendas.

PHP: table structure

I'm developing a website that has some audio courses, each course can have multiple lessons. I want to display each course in its own table with its different lessons.
This is my SQL statement:
Table: courses
id, title
Table: lessons
id, cid (course id), title, date, file
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
Can someone help me with the PHP code?
This is the I code I have written:
mysql_select_db($database_config, $config);
mysql_query("set names utf8");
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<p><span class='heading1'>" . $row['course'] . "</span> </p> ";
echo "<p class='datum'>Posted onder <a href='*'>*</a>, latest update on " . strftime("%A %d %B %Y %H:%M", strtotime($row['date']));
}
echo "</p>";
echo "<class id='text'>";
echo "<p>...</p>";
echo "<table border: none cellpadding='1' cellspacing='1'>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th width='450'>Lesso</th>";
echo "<th>Date</th>";
echo "<th>Download</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['nr'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . strftime("%d/%m/%Y", strtotime($row['date'])) . "</td>";
echo "<td><a href='audio/" . rawurlencode($row['file']) . "'>MP3</a></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
}
?>
One thing that comes to mind is you're starting with lessons and pulling the course details over with it. That means you're going to have a new row per lesson with a joined course. You may want to sort by course (so they're grouped) then (in PHP) keep a tally of "current course". When the course changes, switch to new heading paragraph, table, etc.
Pseudo code:
$currentCourse = null; // intitialize the course
$query = your select sorted by course;
while ($row in $query)
{
if ($currentCourse != $row['course'])
{
if (!is_null($currentCourse))
{
// there was a course before it, close the current one
}
// begin setting up heading1, table beginning, etc.
$currentCourse = $row['course']; // set this as the active course
}
// dump the current row as a table entry
}
// close the table (same code as in the second if statement)
You close the while loop on line 8 of your code block. Remove that '}' on line 8.
Also the HTML element doesn't exists!
I think I know what's your problem. You need a while loop that loops al the "courses" and in that loop you execute a second query where you select the lessons where the course_id is equal to the current course id you're looping. A little dummy code for you.
<?php
while($row = mysql_fetch_assoc(mysql_query("SELECT * FROM courses"))) {
//display the course
while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM lessons WHERE course_id=" . $row['id']))) {
//display the lessons of that course
}
}
?>

Categories