I'm trying to create an HTML table using PHP and MySQL. I have 2 MySQL tables, named coffees, and suppliers, seen here:
Coffees:
Suppliers:
In my HTML table, I wish to display the coffee name, supplier name, and total.
My problem however, is that in order to display the supplier name, I must use the SUP_ID field from the coffees table to reference SUP_NAME from the suppliers table.
My final output aims to be something along the lines of this:
My code is the following:
<?php
$connection_var = new mysqli("server", "user", "pw", "db");
if (mysqli_connect_errno()) {
printf("Connection failed: s\n", mysqli_connect_errno());
exit();
}
$coffees = "SELECT * from coffees";
$suppliers = "SELECT * from suppliers";
$coffeesArr = mysqli_fetch_array($coffees);
$supplierArr = mysqli_fetch_array($suppliers)
echo("<br>");
echo("<table border='1'>");
echo("<tr><td>COF_NAME</td><td>SUPPLIER NAME</td><td>TOTAL</td></tr>");
foreach($resultArr as $row) {
echo("<tr>");
echo("<td>" . $row['COF_NAME'] . "</td><td>" . /* Supplier name (from 2nd table) */ . "</td><td>" . $row['TOTAL'] . "</td><td>");
echo"</tr>");
}
mysqli_close($connection_var);
?>
As seen above, I can easily reference the COF_NAME and TOTAL fields from the first table, however I am at a loss at how to reference the SUP_NAME field from my 2nd MySQL table, as it would require me to use the SUP_ID field from the first table. I would greatly appreciate if someone could guide me on how to achieve this.
A simple INNER JOIN is needed:
select c.cof_name,
s.sup_name,
c.total
from coffees c
inner join suppliers s on c.sup_id=c.sup_id;
Lear more about MySQL
alias
Check MySQL different types of joins:
What is the difference between "INNER JOIN" and "OUTER JOIN"?
https://dev.mysql.com/doc/refman/8.0/en/join.html
you can make an INNER JOIN so it joins both tables
<?php
$connection_var = new mysqli("server", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connection failed: s\n", mysqli_connect_errno());
exit();
}
$sql = "SELECT c.cof_name, s.sup_name, c.total FROM COFFEES c INNER JOIN suppliers s ON c.cof_id=s.sup_id";
$result = mysqli_query($connection_var, $sql) or die(mysqli_error($connection_var));
echo("<br>");
echo("<table border='1'>");
echo("<tr><th>COF_NAME</th><th>SUPPLIER NAME</th><th>TOTAL</th></tr>");;
while($row = mysqli_fetch_array($result ,MYSQLI_ASSOC)) {
echo("<tr>");
echo("<td>" . $row['cof_name'] . "</td><td>" . $row['sup_name'] . "</td><td>" . $row['total'] . "</td>");
echo("</tr>");
}
mysqli_close($connection_var);
?>
Image of the table
For more MySQL documentation about the joins: https://dev.mysql.com/doc/refman/8.0/en/join.html
Related
In my database I have a one-to-many table relationship where one parent can have many kids. The primary key is the parents email. I query to get the kids
$results1 = mysqli_query($con,"
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON '$row[email]' = dirKids.parent
");
Then I loop through and echo the value to my html page
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>".
$row1["kbirthday"]."</td></tr>";
}
}
The problem I am having is that only one parent has kids in my database, but it will print the kids name and birthday 10 times because there are 10 people in my database. How can I get it to only print the child's name and birthday once?
My full code is listed below:
<?php
$con = mysqli_connect("localhost", "username", "password", "db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$results = mysqli_query($con,"SELECT directory.id, directory.fname, directory.lname, directory.address, directory.bdname, directory.birthday, directory.cell, directory.email, directory.sFName, directory.sBirthday, directory.sCell, directory.sEmail FROM directory ORDER BY lname") or die ("couldn't fetch query");
echo "<div class='accordion' id='accordion'>";
// output data of each row
while($row = mysqli_fetch_array($results)) {
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
echo "</table></div>";
if ($row['sFName'] == "" || $row['sFName'] == "undefined") {
echo "<div class='card'><div class='card-header'
id='headingOne'><h5 class='mb-0'><button class='btn btn-link'
type='button' data-toggle='collapse' data-target='#collapse".
$row["id"] ."' aria-expanded='true' aria-controls='collapse".
$row["id"] . "'><h5>".$row["fname"] ."<span id='lnameText'>".
$row["lname"] ."</span></h5></button></h5></div><div
id='collapse". $row["id"] . "' class='collapse'
aria-labelledby='headingOne' data-parent='#accordion'><div
class='card-body'><table id='myUL' class='table'><tr></tr><tr>
<td><h5>Address</h5></td><td>". $row["address"] ."</td></tr>
<tr><td><h5>Birthday</h5></td><td>".$row["birthday"]."</td>
</tr><tr><td><h5>Cell</h5></td><td>". $row["cell"]."</td></tr>
<tr><td><h5>Email</h5></td><td>". $row["email"] ."</td></tr>
</table></div>";
echo "<div class='col-md-6'><h3>Children</h3><table class='table'><tr><th><h5>Name</h5></th><th><h5>Birthday</h5></th>";
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>". $row1["kbirthday"]."</td></tr>";
}
}
echo "</table></div></div>";
?>
Since the data needed for the second while loop comes exclusively from the kids table, just build your SELECT statement for that, forget the join and the WHERE statement looks for only the parents email.
The below code goes inside the primary while loop and replaces the
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
with
//Build the select statement
$sql = "SELECT kname, kbirthday FROM dirKids WHERE parent = '" .$row[email] . "'";
//now run the query
$results1 = mysqli_query($con,$sql);
//uncomment the below to see the results
//var_dump(mysqli_fetch_array($results1));
Your query should look like this;
$select = mysqli_query($db, "SELECT * FROM parents_database WHERE parent_name = '$parent_name'");
while ($row = mysqli_fetch_array($select, MYSQLI_ASSOC)) {
// echo kids here..
}
Not sure what do you need. Since you posted 2 different queries.
But 1st one has wrong approach, hope you need to fix that one.
I think you've meant something like:
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON directory.email = dirKids.parent
WHERE directory.email = '$row[email]'
I am new to PHP and I just cannot figure out my code. I am using MySQL and PHP.
table: person
PK: personID
Other fields: lastName, firstName, hireDate, imgName
table: validMajors
PK: majorAbbrev
Other Fields: majorDesc
(Junction) table: personMajors
personID, majorAbbrev
When I run my code (using NATURAL JOIN) it will display the image, last&first name, and hire date. Which is great! But I need it to display their majors as well (I would like the majorAbbrev to be displayed). It also does not display people who are in the person table but are not in the personMajors table, which is an issue because we have staff members in the person table (who do not have a major since they are not a student)
Here is my code:
<table align="center">
<?php
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
if ( mysqli_connect_errno() ) {
die( mysqli_connect_error() );
}
$sql = "SELECT * FROM person NATURAL JOIN personMajors ORDER BY lastName";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
$columns=4;
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if($i % $columns ==0){
echo "<tr>";
}
echo "<td class='staffImage badgeText frameImage displayInLine'>" . "<img src='images/staff/".$row['imgName'].".jpg'>". "<br>".
"<strong>" . $row['firstName'] . "</strong>" ." ".
"<strong>" . $row['lastName'] . "</strong>" . "<br>" .
"Hire Date: ".$row['hireDate'] ."</td>";
"Major: " .$row['majorAbbrev'] ."</td>"; //Does not display
if($i % $columns == ($columns - 1)){
echo "</tr>";
}
$i++;
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</table>
Any ideas/solution will be greatly appreciated!
Because you are not concatenating your php properly. You ended (;) your echo after displaying the $row["lastName"].
You can try these to join the three tables:
SELECT * FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Or you can define what columns to call in your query:
SELECT person.personID,
person.lastName,
person.firstName,
person.hireDate,
person.imgName,
validMajors.majorAbbrev,
validMajors.majorDesc
FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Then you can call the results with the way you are calling it right now (cleaner version):
echo '<td class="staffImage badgeText frameImage displayInLine">
<img src="images/staff/'.$row["imgName"].'.jpg"><br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>
Hire Date: '.$row["hireDate"].'
Major: '.$row["majorAbbrev"].'
</td>';
(Second try): Is the person to major relationship one to one or one to many?
OK, this SELECT Statement should work:
SELECT person.*, validMajors.* FROM person AS p, validMajors AS vm, personMajors AS pm WHERE p.personID = pm.personID AND pm.majorAbbrev = vm.majorAbbrev
I have three tables:
I want to display 'Event Details' which shows attending employee details (listo f employee ids from the 'attending_employees table > corresponding employee details form 'employee' table), what team they belong to (from the club_teams table) and the event details from the 'club_events' table).
Currently I am using multiple mysqli queries to display this information however cannot get my head around pulling the data from the database in one query (ie: LEFT JOIN). Your assistance would be greatly appreciated!
Below are the queries i am currently using:
$query = msqli_query($con, "SELECT * FROM attending_employees")or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){
while($attending = mysqli_fetch_array($query)){
foreach($attending['club_event']){
$eventid = $attending['club_event'];
$query = msqli_query($con, "SELECT * FROM club_events WHERE club_event_id = '$eventid'")or die(mysqli_error($con));
while($event_details = mysqli_fetch_array($query)){
// Echo event details
}
}foreach($attending['employee']){
$empid = $attending['employee'];
$query = msqli_query($con, "SELECT * FROM employees WHERE employee_id = '$empid'")or die(mysqli_error($con));
while($event_employees = mysqli_fetch_array($query)){
// Echo employee details
}
}foreach($attending['team']){
$teamid = $attending['team'];
$query = msqli_query($con, "SELECT * FROM club_teams WHERE clb_team_id = '$teamid'")or die(mysqli_error($con));
while($event_team = mysqli_fetch_array($query)){
// Echo team details
}
}
}
}
This method is highly inefficient and wasteful since its retrieving duplicate data (ie: all repeated 'club_event_id's in the 'attending_employees' table.)
Try this:
$query = msqli_query(
$con,
"SELECT"
. " attending_employees.*"
. ", club_events.*"
. ", employees.*"
. ", club_teams.*"
. " FROM"
. " attending_employees"
. " LEFT JOIN club_events ON club_events.club_event_id = attending_employees.club_event"
. " LEFT JOIN employees ON employees.employee_id = attending_employees.employee"
. " LEFT JOIN club_teams ON club_teams.clb_team_id = attending_employees.team"
) or die(mysqli_error($con));
I am trying to get data from two tables:
$con = getDbConnect();
$edit = $_GET['edit'];
if (mysqli_connect_errno($con)) {
"Failed to connect to MySQL: " . mysqli_connect_error();
} else {
$result = mysqli_query($con, "SELECT * FROM admininfo where email='" . $edit . "'");
$results = mysqli_query($con, "SELECT * FROM adminaccount where email='" . $edit . "'");
while ($admininfo = mysqli_fetch_array($result, $results)) {
You use a single query no matter how many tables you're selecting from, e.g.
SELECT a.*, b.* FROM table1 a, table2 b where a.id = ? AND b.id = ?
Then you fetch what you need from the result, take a look at the docs for that.
-- and, of-course, don't use select *.
I am trying display those values from database but it shows an error which is written in if condition plz tell me where i am doing wrong????
$sql1 = "SELECT * FROM Batch b, Vendor v, Product p WHERE 'v.id' = 'b.id', 'p.id' = 'b.id' and 'b.batch_no' = $batchno";
$retval = mysqli_query($conn,$sql1);
if(!$retval)
{
die('Could not get data:' . $conn->connect_error);
}
else
{
echo "<input type = 'submit' value = 'Print Bill'><br>";
echo "<h3>Bill</h3>";
while($row = mysqli_fetch_array($retval,MYSQL_ASSOC))
{
echo "Vendor Name :{$row['name']} <br> " .
"Batch No:{$row['batchno']} <br> " .
"Product Size:{$row['product_size']} <br> " .
"Product Price Per Unit:{$row['product_price']} <br> " .
"Product Quantity:{$row['quantity']} <br> " .
"------------------------------<br>";
}
}
first check your connection if your connected on your database
and try
"SELECT * FROM batch b Inner join Vendor v on v.id=b.id inner join Product p on p.id=b.id where b.batch_no=".$batchno
You have to join the tables and then use 'on' to tell it how to link the tables.
http://dev.mysql.com/doc/refman/5.0/en/join.html
Also not sure what $batchno but that maybe opening your query to injections. http://en.wikipedia.org/wiki/SQL_injection
There is and instead of , in your sql query
$sql1 = "SELECT * FROM Batch b, Vendor v, Product p WHERE 'v.id' = 'b.id' and 'p.id' = 'b.id' and 'b.batch_no' = $batchno";