Join two database tables and output resutls to HTML table - php

For my current progress I need to create a table like the one below
pid cid eid name value
1 1 4 name ab
2 1 5 amt 2
3 1 4 name cd
4 1 5 amt 4
Instead of creating the table like this
pid cid name amt
1 1 ab 22
2 1 cd 4
Anyhow created table as my wish with the below code
<table width="1204" height="100" border="1">
<tr>
<?php $sqlname="Select * From elements where cat_id='1' order by e_id ";
$resname=mysql_query($sqlname);
while($rowname=mysql_fetch_array($resname)){
?>
<td colspan="2"><?php echo $rowname['lable_name']; ?></td>
</tr>
<tr>
<?php $i=0;
$sqlprolist="select value from products_list where name='".$rowname['lable_name']."' and e_id='".$rowname['e_id']."'";
$resprolist=mysql_query($sqlprolist);
while($rowprolist=mysql_fetch_array($resprolist)){
$i++;
?>
<td><?php echo $rowprolist['value'];?></td>
<?php if($i%8==0){
?>
<tr></tr>
<?php }?>
<?php }?>
</tr>
<?php }?>
</table>
But I don't have any idea to retrieve data from the table for processing.
thanks
as by following martin the table created as like the below table
pid cid eid name value
12 1 4 name abc
1 1 4 name cde
13 1 5 code 12
2 1 5 code 14
how to split up the data
like
name code breeder quality size
abc 12 121 121 22
acfd 34 164 22 22
thanks

It's difficult to help you without seeing database structure. Please share it with us, you might get better answers.
Anyway, I suppose you have two tables, elements and products_list. It looks like you need to lookup the value column in the products_list for every row in the elements table. You can merge these table into one result set using a single SQL query:
SELECT e.p_id, e.cat_id, e.e_id, e.lable_name, p.value
FROM elements e, products_list p
WHERE e.cat_id='1' AND
p.name = e.lable_name AND p.e_id = e.e_id
ORDER BY by e.e_id
Note that the e.p_id is just a guess, you have not shared with us, where the "pid" column value gets from. Also not sure, if you actually need to match the rows using the p.name = e.lable_name. If e_id is primary key, you might do with p.e_id = e.e_id only.
What's the point of cid column? If it is indeed the cat_id column in database, why do you need it in HTML table, if you filter the elements to cat_id=1 anyway? Was that intentional?
You can now take the results of the query and simply output it to a HTML table row by row like:
<table width="1204" height="100" border="1">
<tr>
<th>pid</th>
<th>cid</th>
<th>eid</th>
<th>name</th>
<th>value</th>
</tr>
<?php
$sqlname =
"SELECT e.p_id, e.cat_id, e.e_id, e.lable_name, p.value ".
"FROM elements e, products_list p ".
"WHERE e.cat_id='1' AND ".
"p.name = e.lable_name AND p.e_id = e.e_id".
"ORDER BY e.e_id";
$resname = mysql_query($sqlname);
while ($row = mysql_fetch_array($resname))
{
?>
<tr>
<td><?php echo $row['p_id'];?></td>
<td><?php echo $row['cat_id'];?></td>
<td><?php echo $row['e_id'];?></td>
<td><?php echo htmlspecialchars($row['lable_name']);?></td>
<td><?php echo $row['value'];?></td>
</tr>
<?php
}
?>
</table>
This is just a first step. It's unlikely this is correct answer. But I hope it helps you understand, what are you trying to do and to your question.
This is hardly production-grade code. But I wanted to do as little changes as possible, so you can see, what is the actual change from your code.
Also note that the mysql_ functions are deprecated. See the big red box on PHP documentation page.

Related

PHP using PDO with two data tables

I want the status column to show the value "free" when there is no corresponding record in the device_transactions table, or there is a corresponding record in the device_transactions table with the returned_date blank field
My desired return result is like this
That's all I can do right now
How can I print row #4 while the device_transactions table has no corresponding records in the devices table?
The 2 data tables
Table devices:
id
name
1
Laptop01
2
Laptop02
3
Laptop03
4
Laptop04
Table device_transactions:
id
device_id
start_transaction_plan
end_transaction_plan
returned_date
1
1
2021-12-10 14:20:43
2021-12-12 07:00:00
2021-12-12 9:30:23
2
2
2021-12-11 10:10:20
2021-12-15 15:30:00
2021-12-16 7:30:45
3
3
2021-12-12 19:03:00
2021-12-21 08:00:00
NULL
<table id="myTable">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$sql = $conn->prepare("SELECT devices.id, devices.name, device_transactions.returned_date
FROM devices, device_transactions WHERE devices.id = device_transactions.device_id ");
$sql->execute();
$result = $sql->setFetchMode(PDO::FETCH_ASSOC);
foreach ($sql->fetchAll() as $row) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php
if($row['returned_date'] !== null ){
echo "free";
}
else{
echo "borrowed";
}
?></td>
</tr>
<?php }
?>
</tbody>
</table>
You want to use LEFT JOIN, instead of FROM devices, device_transactions (which is an INNER JOIN).
SELECT devices.id, devices.name, device_transactions.returned_date
FROM devices
LEFT JOIN device_transactions ON devices.id = device_transactions.device_id
Just use a simple LEFT JOIN and you'll get all the record:
OK I've made a little edit so my answer is not the same as already givven and this will help you to avoid checkinh if return date is null or not
SELECT d.id as deviceid, d.name as devicename, c.returned_date as returndate
FROM device d
LEFT JOIN device_transactions c ON c.device_id = d.id;
Edit of the query - so now if there is no record or return date is null you'll get 'free' as returntype else you get 'borrowed'(you can put whatever you want of course...) So now no need in php to check if $row['return_date'] == null just output the result from the query:
SELECT d.id as deviceid, d.name as devicename,
CASE WHEN c.returned_date IS NULL THEN 'free' ELSE 'borrowed' END as returntype
FROM device d
LEFT JOIN device_transactions c ON c.device_id = d.id;
See it working here
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=32db15fbb2b00d780196ea879e6f7d20
Edited result:
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4edc860aa39461f2c5e6655bbca77d66

Duplicate results from mysql

I'm new to php, but I have already made some query's for my webshop.
I have a little problem now with making the invoice.
I'm trying put the invoice data from the database in a table in my website, but it duplicates itself.
Product_id | Product name | amount | price | subtotal|
2 kippensoep 1 €3 €3
2 kippensoep 1 €3 €3
2 kippensoep 1 €3 €3
4 Loempia's 1 €10 €10
4 Loempia's 1 €10 €10
4 Loempia's 1 €10 €10
4 Loempia's 1 €10 €10
So as you can see, the product_id , product_names are duplicated.
It's strange because in the database it isn't duplicated.
Here's the php code.
<?php
$maxfac1 = mysql_fetch_array(mysql_query("SELECT MAX(transactie.factuur_id) FROM transactie , account WHERE transactie.id = $session_user_id"));
unset ($maxfac1[0]);
$maxfactuur_id = implode (" ",$maxfac1);
$productinfo = mysql_query("SELECT * FROM producten, transactie, factuur WHERE producten.product_id = factuur.product_id AND factuur.factuur_id = $maxfactuur_id AND factuur.gebruikers_id= $session_user_id");
$totaal=0;
$subtotaal=0;
while ($row = mysql_fetch_array($productinfo))
{
?>
<tr>
<td><?php echo $row['product_id']?></td>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['amount'] ?></td>
<td>€<?php echo $row['price'] ?></td>
<?php $subtotaal = ($row['price']*$row['amount']);?>
<td>€<?php echo "$subtotaal" ;$totaal+= $subtotaal;?></td>
</tr>
<?php
}
?>
?>
I hope you guys can help me and find a solution.
EDIT
session_user_id checks if the user is logged in. Then it returns the id from the user who is logged in.
You are missing a link with the transactie table. So you have a Cartesian join appearing.
Add the proper where condition to fix that.
As you didn't provide any table structure, I can't help you more than that!
edit
on an other level, do not use mysql extension since it is deprecated!
Try to check rows are unique. And add GROUP BY producten.product_id to your query.
Try to add the DISTINCT keyword.
$productinfo = mysql_query("SELECT DISTINCT * FROM producten, transactie, factuur WHERE producten.product_id = factuur.product_id AND factuur.factuur_id = $maxfactuur_id AND factuur.gebruikers_id= $session_user_id");

Values inserted through MySQLi could not be fully inserted with mysqli_insert_id

Good Day, this is just a follow-up question from Referrence 1 here on stackoverflow. Though it was now being solved partially, I still have issues with eid. The multiple insert through mysqli is a bit working (I just said a bit since only 4 our of 6 tables were being inserted with values), but when I checked if the foreign key for eid are also been copied by mysqli_insert_id() I'm surprised to see that the foreign key eid got 0 values.
It was like this (NOTE: The ff: data are not the actual one):
Table: Employee [eid is it's primary key]
eid employee_name address etc
1002 employee A Beside U ♥
1003 employee B Pluto ♥
Table: Contact [eid is it's foreign key]
eid telno email
0 911 kingCorbra#hey.com
0 *** universe#hey.com
Table: Work Experience [eid is it's foreign key]
eid Company Name start date end date
0 Windows Macintosh 2012-12-01 2012-12-02
0 Micro Entertainment LG 2012-12-31 2013-01-01
*Other Tables are not included in the samples but part of the query.*
As you know, I have used mysqli_insert_id() during the insert statement again please see the Referrence 1, and luckily it work but only for 4 out of 6 actual tables. And when I checked the eid column it shows 0 values.
Here is my select statement (not the real one):
` <table cellspacing="0" width="100%">
<thead>
<tr>
<th><strong>Name:</strong></th>
<th><strong>Date of Birth:</strong></th>
<th><strong>Birthplace:</strong></th>
<th><strong>Gender:</strong></th>
<th><strong>Email Add:</strong></th>
<th><strong>Contact#:</strong></th>
<th><strong>Address:</strong></th>
</tr>
</thead>
<?php
include('db.php');
$sql=mysqli_query("SELECT emp.eid,emp.fname,
emp.mname,emp.lname,
emp.age,emp.gender,
emp.birthday,emp.birthplace,
emp.citizenship,emp.status,
emp.sss,emp.philhealth,
emp.tin,emp.height,
emp.weight,
con.address,
con.province,con.postcode,
con.telno,con.mobile,
con.email,con.alternate,
educ.elem,
educ.egrad,educ.high,
educ.hgrad,educ.college,
educ.cgrad,
ems.position,ems.hireDate,ems.job_desc,ems.basic,ems.salary,
w.company_name,w.position,w.desc,w.startDate,w.endDate,
fam.fatherName,fam.motherName,fam.sibling,fam.spouse,fam.children
FROM employee AS emp INNER JOIN contact AS con ON con.eid='emp.eid'
INNER JOIN educ AS educ ON educ.eid='emp.eid'
INNER JOIN employment AS ems ON ems.eid='emp.eid'
INNER JOIN work AS w ON w.eid='emp.eid'
INNER JOIN family AS fam ON fam.eid='emp.eid' WHERE emp.eid='$id'");
$counter=0;
while($row=mysqli_fetch_assoc($sql))
{
$cname = $row['name'];
$cbday = $row['birthday'];
$pob = $row['pob'];
$cgen = $row['gender'];
$email = $row['email'];
$contact= $row['contact'];
$add = $row['address'];
if($counter%2)
{
?>
<tbody>
<?php } else { ?>
<tr>
<?php } ?>
<td><?php echo $cname; ?></td>
<td><?php echo $cbday; ?></td>
<td><?php echo $pob; ?></td>
<td><?php echo $cgen; ?></td>
<td><?php echo $email; ?></td>
<td><?php echo $contract; ?></td>
<td><?php echo $add; ?></td>
</tr>
</tbody>
<?php
$counter++;
}//while-end
?>
</table>`
To make things much weird, let me tell you that when I tried to display values using mysqli_fetched_assoc() the query doesn't seem to work as in on my index page nothing else displays. Though the db has its record. But when I used mysql [though many have claimed it to be deprecated] it seems to work fine eventhough I had mysqli used for the insert statement. You guys get my point right? I used mysqli for insert statement and mysql for display and it works fine except for the eid of course.
Any idea?
$sql=mysql_query
Will never ever work with
mysqli_insert_id
^
You need to use the same API for both calls. Use MySQLi throughout.

How to remove duplication in the retrieval results?

Please i need a help am beginner in php and my sql, i want to retrieve all students names who registered in each level(1 OR 2 OR 3 OR 4) this is my code.
<form id="form1" name="form1" method="post" action="">
<table border="1" align="center" class="tftable">
<?php
$lvlid = $_GET['id'];
$sql2 = "select * from `course` where acadlevel='$lvlid' ";
$res2= mysql_query($sql2,$con_mark_entry);
while($row2 = mysql_fetch_row($res2))
{?>
<?php } ?>
<tr>
<th id="h7">Serial NO.</th>
<th id="h7">Student NO.</th>
<th id="h7">Student Name</th>
</tr>
<?php
$s=1;
$sql ="SELECT student.stud_id,student.stud_name, course.title, enrollment.grade FROM student, course, enrollment WHERE course.acadlevel ='".$_GET['id'] ."' AND course.code = enrollment.code AND student.stud_id = enrollment.stud_id";
$res= mysql_query($sql,$con_mark_entry);
while($row1 = mysql_fetch_row($res)){
?>
<tr>
<td><?php echo $s?> </td>
<td><?php echo $row1[0]?></td>
<td id="name"><a href="report6.php?id=<?php echo $row1[1]?>"> <?php echo $row1[1]?> </td>
</tr>
<?php
$s++;
}
?>
</table>
My Problem is for example if the student registered in three course at level 1 ,he would appear three times, i want to remove this duplication. HOW?
The result as follow:
serial no student no student name
1 101 adam nagdy
2 101 adam nagdy
3 101 adam nagdy
4 102 shima najm
Thanks in advance
Use DISTINCT keyword. It removes duplicate result rows.
Search for "distinct" in this page.
SELECT DISTINCT std.stud_id,std.stud_name, enr.grade -- , crs.title
FROM student std
LEFT OUTER JOIN enrollment enr ON std.stud_id = enr.stud_id
LEFT OUTER JOIN course crs ON crs.code = enr.code
WHERE course.acadlevel ='YOUR_ID'
And use JOIN to join. ;) It is better than joining with WHERE (even if it works).
Try using GROUP BY course.acadlevel at the end of your query.
That should reduce the results to one row per academic level, instead of 3, if the student registered for 3 classes.
Also, as John Conde has commented, mysql_ prefixed functions are deprecated and will be removed from future versions of PHP. You should instead use Mysqli or PDO_MySQL. And you should never use $_GET[]/$_POST or any other variables with user input in your MySQL queries without sanitizing them.

Combine total count for entries in 2 SQL tables

I can't seem to find the right way to do this so I was hoping someone could give me some direction?
The SQL Database is structured like this (I've removed the irrelevant stuff):
Requests
R_ID R_FulfilledBy
1 Bob
2 Craig
3 Bob
SIMs
SM_ID SM_FulfilledBy
1 Bob
2 Craig
3 Bob
I'm hoping to end up with this output:
Fulfilled By Requests
Bob 4
Craig 2
Here's my PHP/HTML:
<div id="table">
<?php
//Connect to MySQL Database
$connection = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass);
mysql_select_db($runnerdbName, $connection) or die("MysQL Error");
$query = "SELECT R_FulfilledBy, COUNT(R_ID) FROM Requests GROUP BY R_FulfilledBy ORDER BY COUNT(R_ID) DESC";
$result = mysql_query($query) or die(mysql_error());
?>
<!-- Number of Runners (Counts total number of records in Requests table) -->
<table border='0' width='50%'>
<tr>
<th>Runners Fulfilled</th>
<tr><td><?php
$query = mysql_query("SELECT * FROM Requests");
$number=mysql_num_rows($query);
echo $number;
?>
</td></tr>
</table>
<!-- Fulfillment Stats -->
<table border='0' width='50%'>
<tr>
<th>Name</th>
<th>Runners Fulfilled</th>
</tr>
<?
// Print out result (I want this to calculate requests fulfilled by each user in 'Requests' and 'SIMs' table)
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>". $row['R_FulfilledBy'] ."</td>";
echo "<td>". $row['COUNT(R_ID)'] ."</td>";
echo "</tr>";
}
?>
</table>
At present it's only calculating the records from the 'Requests' table :(
You could union all the two tables together in a subquery:
select FulfilledBy
, count(*)
from (
select R_FulfilledBy as FulfilledBy
from Requests
union all
select SM_FulfilledBy
from SIMs
) as SubQueryAlias
group by
FulfilledBy
Use union all instead of union because the second eliminates duplicates; which would give everyone a maximum count of 1.
I'd go with this:
SELECT R_FulfilledBy, COUNT(*) +
( SELECT COUNT(*) FROM SIMs WHERE R_FulfilledBy = SM_FulfilledBy )
FROM Requests GROUP BY R_FulfilledBy

Categories