I am trying to get all the values from one table and some values from another table and display them using php and html. It is a demo point of sale program that I am trying to modify.
The section I am trying to modify is the sales report page, where initially I have TRANSACTION ID
, DATE
, INVOICE NUMBER
, AMOUNT
and REMARKS
. I would like to add some values from another table (i.e. sales "NAME" and "QTY").
Here is what I did:
<?php
include('../connect.php');
$d1=$_GET['d1'];
$d2=$_GET['d2'];
$result = $db->prepare("SELECT sales.* , sales_order.name, sales_order.qty FROM sales,sales_order WHERE date BETWEEN :a AND :b");
$result->bindParam(':a', $d1);
$result->bindParam(':b', $d2);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record">
<td>STI-000<?php echo $row['transaction_id']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['invoice_number']; ?></td>
<tf><?php echo $row{'invoice_number'};?></td>
<td><?php
$dsdsd=$row['amount'];
echo formatMoney($dsdsd, true);
?></td>
<td><?php echo $row['type']; ?></td>
</tr>
<?php
}
?>
</tbody>
<thead>
<tr>
<th colspan="4" style="border-top:1px solid #999999"> Total </th>
<th colspan="2" style="border-top:1px solid #999999">
<?php
function formatMoney($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
$d1=$_GET['d1'];
$d2=$_GET['d2'];
$results = $db->prepare("SELECT sum(amount) FROM sales WHERE date BETWEEN :a AND :b");
$results->bindParam(':a', $d1);
$results->bindParam(':b', $d2);
$results->execute();
for($i=0; $rows = $results->fetch(); $i++){
$dsdsd=$rows['sum(amount)'];
echo formatMoney($dsdsd, true);
}
?>
</th>
</tr>
</thead>
</table>
Assuming the key linking the tables sales
and sales_order
are the field invoice_number
you have to join the two tables using an INNER JOIN (or a LEFT JOIN depending on your needs) as following :
$result = $db->prepare("SELECT sales.* , sales_order.name, sales_order.qty FROM sales INNER JOIN sales_order ON sales.invoice_number = sales_order.invoice_number WHERE sales.date BETWEEN :a AND :b");
If the key linking the two tables is something else, then just update the ON sales.invoice_number = sales_order.invoice_number
to match the good column name
Also, do not forget to add the name of the table before each fields when you join tables because if you have the same field name in more than one table it will give you an error because mysql won't know in which table it has to get the data from.