Displaying multiple tables depending on data available - php

I am trying to display data from multiple tables on one page but I need to do different queries to get all the people to show up. How do I format a query where it will select data from the job/jobSearch table if there is data that matches with the studentID from the student and major tables or select from the education table if there is data that matches the studentID. Both job/jobSearch and the education tables will not have data for the same student at the same time because they will either be choosing that they are employed after graduation or continuing their education so if they choose education they skip the questions regarding employment and vice versa.
<?php
include('includes/db_connect.php');
//include('student.php');
$query_student="SELECT *
FROM student
JOIN major
ON student.studentID=major.studentID
JOIN jobSearch
ON major.studentID=jobSearch.studentID
JOIN job
ON jobSearch.studentID=job.studentID
JOIN education
ON job.studentID=education.studentId";
$result_student=mysqli_query($conn, $query_student) or die(mysqli_error($conn));
echo '<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Graduate Year</th>
<th>Major</th>
<th>Activity After Graduation</th>
</tr>';
while($row = mysqli_fetch_array($result_student))
{
echo'<tr>'; // printing table row
echo '<td>' . $row['firstName'] . '</td>';
echo '<td>' . $row['lastName'] . '</td>';
echo '<td>' . $row['gradDate'] . '</td>';
echo '<td>' . $row['major'] . '</td>';
echo '<td>' . $row['activity'] . '</td>';
echo'</tr>'; // closing table row
}
echo '</table>';
$conn->close();
?>

Related

Display result if Table names are the same due to INNER JOIN

I don't know how to Explain my problem so here it goes
I have a Table called asalink with codes linked to names in a table called asatbl
I'm joining the tables but need the same Field to Display twice due to a different key
Please see my code Maybe this explains it better
$sele = "SELECT asatbl_1.asaName, asatbl_1.asaSurname, asatbl.asaName, asatbl.asaSurname, asalink.linkammount
FROM asatbl AS asatbl_1 INNER JOIN (asalink INNER JOIN asatbl ON asalink.asaid = asatbl.asaid) ON asatbl_1.asaSales_ref = asalink.asaSales_ref
WHERE asalink.asaSales_ref=1001";
$result = mysql_query($sele);
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ASA Name</th> <th>ASA Surname</th> <th>Recipient Name</th> <th>Recipient Surname</th> <th>Amount</th></tr>";
if($mak = mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo '<td>' . $row['asaName'] . '</td>';
echo '<td>' . $row['asaSurname'] . '</td>';
echo '<td>' . $row['asatbl_1.asaName'] . '</td>';
echo '<td>' . $row['asatbl_1.asaSurname'] . '</td>';
echo '<td>' . $row['li nkammount'] . '</td>';
echo '<td>Edit</td>';
//echo '<td>Delete</td>';
echo "</tr>";
as you can see I used asatbl_.asaName and asatbl_1.Surname but does not work
Thanks in advance for help
Regards
Use an alias for the field names in result:
SELECT asatbl_1.asaName as fld1, asatbl_1.asaSurname as fld2, ... and so on.
Then to retrieve data reference the alias in resultset
$row['fld1']
$row['fld2']
...
Hopes this helps
I see a problem with the way you are trying to get the values of the fields using $row['asatbl_1.asaName'] and $row['asatbl_1.asaSurname']. You have to simply use $row['asaName'] and $row['asaSurname'] by removing table names before the column names.
After running any SQL query in PHP which has columns fetched along with table name using .(dot) through notations like - SELECT **table_name.column_name** FROM table_name you should not access the column values in the PHP query result with the table name prefixed to it which you are doing in $row['asatbl_1.asaName'] and $row['asatbl_1.asaSurname'].

Display column from SQL query with same name

how can I display the name of both teams (lteam and vteam)? Query works now... This is a screenshot of the SQL results:
http://prntscr.com/f9mkqh
$sql = "
SELECT *
FROM fixtures
LEFT
JOIN teams AS a
ON fixtures.lteam = a.id
LEFT
JOIN teams AS b
ON fixtures.vteam = b.id
WHERE date_ko = '2017-05-19'
";
echo '<table>';
echo '<tbody>';
foreach($pdo->query($sql) as $row)
{
echo '<tr>';
echo '<td>' . $row['lteam'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>-</td>';
echo '<td>' . $row['vteam'] . '</td>';
echo '<td>' . $row['b.name'] . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
Thanks!
The SQL result header is somewhat confusing, and as I don't know fully how the tables and schemas are structured, I have to assume you are having trouble with getting the name attribute from the teams table, as this is joined in two times.
You will need to select the columns explicitly and naming them something else for this to work. For example:
SELECT *, `a`.`name` as `team1name`, `b`.`name` as `team2name` FROM fixtures [...]
Now you should be able to grab the team names under their assigned aliases.

sum mysql table column data where id is the same in php SELECT statement

I need to display an html table with data from two different tables, invoices and lineitems where invoices.id=lineitems.invoiceid. However, each row in invoices can have several lineitem rows that connect to it as invoices is the customers' order and lineitems is the table containing all the products for each order. I need to sum up the values from lineitems.quantity for every row where the invoiceid is the same so my html table can display the total quantity for the order. Is there a way to do that within my select statement for my html table?
Right now, when I display my table, I get the same invoice order listed repeatedly for each lineitem row associated with it (where the only html table column data that's different per row is the quantity).
MySQL SELECT statement:
$sql = "SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, FORMAT((lineitems.width * lineitems.height) /144, 2 ) AS sqft, lineitems.quantity AS qty, FORMAT((invoices.totalprice / ((lineitems.width * lineitems.height) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / lineitems.quantity), 2) AS avgunitrevenue
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."' AND invoices.stagestatus IN (". implode(',', array_map(function($item) {return '"' . $item . '"'; }, $revenue_check)) .")
ORDER BY invoices.id DESC";
//Display daterange and table.
echo 'Displaying results for: '.$revenuefrom.' to '.$revenueto.'. '.'<BR><BR><BR>';
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<tr>
<th>Customer</th>
<th>Stage Status</th>
<th>SG</th>
<th>Revenue</th>
<th>SQ FT</th>
<th>AVG Revenue Per SQ FT</th>
<th>Number of Units</th>
<th>AVG Revenue Per Unit</th>
</tr>";
if ($result = $conn->query($sql)) {
// fetch associative array
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['stagestatus'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
}
echo "</table>";
NOTE: Due to the pre-existing code design (I inherited...), setting up a trigger is not an option and trying to run the calculation and insert that value into another column in invoices is seeming impossible from the application side (again due to the way the previous programmer designed the update/insert for invoices and lineitems). If anyone is curious about that code, please refer to the following link where I asked how complete this same task via the application side:
get sum() value from user input going into one table and store in another table using php
Any suggestions are greatly appreciated as I have tried several different methods for achieving the desired outcome.
Thank you!

Filter already output mysql data in HTML table

I have my MySQL data output into a HTML table successfully and exactly how I want it. Now I'd like to filter this data based on multiple dropdown values and a submit button. I've looked around in tutorials and other questions but can't find what I'm looking for. Here's how I output:
$fetchResult = "SELECT a.MembershipID, a.FirstName, a.Surname, t.RaceID, r.RaceName, t.Time, r.RaceID, r.ClubYear
FROM Athlete AS a
INNER JOIN Time AS t
ON a.MembershipID=t.MembershipID
INNER JOIN Race AS r
ON t.RaceID=r.RaceID
ORDER BY a.Surname";
$result = $mysqli->query($fetchResult);
//Start table
echo "<table>";
echo "<tr>
<th>First Name</th>
<th>Surname</th>
<th>Race</th>
<th>Time</th>
<th>Club Year</th>";
// Loop through database
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['Surname'] . '</td>';
echo '<td>' . $row['RaceName'] . '</td>';
echo '<td>' . $row['Time'] . '</td>';
echo '<td>' . $row['ClubYear'] . '</td>';
}
echo "</tr></table>";
Now I have 4 dropdowns also populated by data from the database. What I'd like to happen is, the user picks an option between 1 and 4 dropdowns and the data in the HTML gets filtered but I can't get this to work. Here is what I have so far:
if (!empty($clubYear)) {
$fetchResult = "SELECT a.MembershipID, a.FirstName, a.Surname, t.RaceID, r.RaceName, t.Time, r.RaceID, r.ClubYear
FROM Athlete AS a
INNER JOIN Time AS t
ON a.MembershipID=t.MembershipID
INNER JOIN Race AS r
ON t.RaceID=r.RaceID
WHERE r.ClubYear='$clubYear'
ORDER BY a.Surname";
}
$result = $mysqli->query($fetchResult);
So I check to see if the dropdown is empty, if not, apply a query with a WHERE filter. This just makes the page refresh and go to a "no data received" page. Where am I going wrong? The filter should be applied based on what's been selected in the dropdown but without explicitly stating what that dropdown equals i.e= if $clubYear == "whatever", then WHERE r.ClubYear="whatever" - I'd like to just filter through passing the variable.
Thanks.

PHP MySQL - Multiple Select Queries returned in while loop

I have the following code which works fine however historically and again now I want to (if possible) add a third select statement to collect further information and return it in my while loop i.e. as $row2.
Is there any way I can do this or will I have to rehash my code completely to make it work?
Any help or guidance will be gratefully received. Current code is as below:
mysql_select_db("jbsrint", $con);
$result = mysql_query("SELECT *, DATE_FORMAT(Date_Registered, '%d-%m-%Y') AS Date_Registered, DATE_FORMAT(Date_Last_MOT, '%d-%m-%Y') AS Date_Last_MOT, DATE_FORMAT(Date_Last_Tax, '%d-%m-%Y') AS Date_Last_Tax FROM Veh_List ORDER BY ID DESC");
$DUE_DATES = mysql_query("SELECT *, DATE_FORMAT(MOT_DUE_DATE, '%d-%m-%Y') AS MOT_DUE_DATE, DATE_FORMAT(Date_Tax_Due, '%d-%m-%Y') AS Date_Tax_Due FROM due_dates ORDER BY ID DESC");
echo "<table border='1'>
<tr>
<th>Vehicle Reg</th>
<th>Vehicle Make</th>
<th>Vehicle Model</th>
<th>Vehicle Colour</th>
<th>Date Registered</th>
<th>Date Of Last MOT</th>
<th>MOT Due</th>
<th>Date Of Last Tax</th>
<th>Tax Due</th>
<th>Vehicle Driver</th>
<th>Vehicle Driver Tel</th>
</tr>";
while($row = mysql_fetch_array($result) and $row1 = mysql_fetch_array($DUE_DATES))
{
echo "<tr>";
echo "<td class=\"td1\">" . $row['Vehicle_Reg'] . "</td>";
echo "<td >" . $row['Vehicle_Make'] . "</td>";
echo "<td class=\"td1\">" . $row['Vehicle_Model'] . "</td>";
echo "<td>" . $row['Vehicle_Colour'] . "</td>";
echo "<td class=\"td1\">" . $row['Date_Registered'] . "</td>";
echo "<td>" . $row['Date_Last_MOT'] . "</td>";
echo "<td class=\"td1\">" . $row1['MOT_DUE_DATE'] . "</td>";
echo "<td>" . $row['Date_Last_Tax'] . "</td>";
echo "<td class=\"td1\">" . $row1['Date_Tax_Due'] . "</td>";
echo "<td>" . $row['Vehicle_Driver'] . "</td>";
echo "<td class=\"td1\">" . $row['Vehicle_Driver_Tel'] . "</td>";
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?>
You should not use a separate query for each table. Instead you should use JOIN to retrieve related data from multiple tables in a single query:
SELECT
veh_List.col1,
veh_List.col2,
due_dates.col3,
...etc...
FROM veh_List
JOIN due_dates ON veh_List.id = due_dates.id
-- add more joins here if you need data from more tables
ORDER BY veh_List.id DESC
You should learn about the JOIN keyword and the various possibilities this provides, including understanding the difference between INNER JOIN and OUTER JOIN.
What is the difference between "INNER JOIN" and "OUTER JOIN"?
I believe you can simply add another statement and combine it in the same fashion as you had now but my suggestion is to use the opportunity that you are modifying the code and merge the SQL queries into one.
Also, looking at your database design - is there one-to-one relation between the due dates and registered cars? If so, why not merge the two tables together? (Of course, I can only see the columns you are using in your select queries).
Furthermore, it seems a bit dangerous to rely on the ordering to match up the records - what if one row from due dates is removed?

Categories