how to pull up the last entry of each product - php

I have an inventory table that gets updated with each transaction. Currently there are 4 products, but at some point there may be more. The following is the table I used to pull everything.
<?php
$db = new mysqli('', '', '', 'inventory');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT * FROM inventory";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
echo "<table style='border: 2px;font-family: tahoma;'><caption><b>Entire Database Contents</b></caption><tr><td>ID</td><td>Time Stamp</td><td>Staff</td><td>Client</td><td>Needed</td><td>Product</td><td>Amount</td><td>Totals</td><td style='width: 200px;'>Comments</td></tr>";
while($row = $result->fetch_assoc()){
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['timeStamp'] . '</td>';
echo '<td>' . $row['staff'] . '</td>';
echo '<td>' . $row['client'] . '</td>';
echo '<td>' . $row['dateNeeded'] . '</td>';
echo '<td>' . $row['product'] . '</td>';
echo '<td>' . $row['amt'] . '</td>';
echo '<td>' . $row['tot'] . '</td>';
echo '<td>' . $row['comments'] . '</td></tr>';
}
echo "</table>";
?>
What I'd like to do is to pull ONLY the most recent entries of each product. I'm thinking maybe DISTINCT and LAST probably comes into play here but have no idea how to set it up. Any pointers?

You should create date_added field and sort by it:
$sql = "SELECT * FROM inventory ORDER BY date_added DESC";

You need to select only the products with MAX timestamp:
SELECT i.* FROM inventory i
JOIN (SELECT product, MAX(timestamp) timestamp FROM inventory GROUP BY product) i2
ON i2.product = i.product
AND i2.timestamp = i.timestamp

This should work:
select distinct product, id, timeStamp, staff, client, dateNeeded, amt, tot, comments from inventory order by timestamp desc;

Related

How to join two tables with multiple common fields for search filter

I have 2 table bpi_registration and bpi_teamProfile. The fields in bpi_registration are : id, id_school, first_name,last_name,email,city,state,country and fields in bpi_teamProfile table are id_team, team_name, id_student1, id_student2, id_student3 now id_student1, id_student2, id_student3 contains the same id of students that were in bpi_registration. I am not sure how to connect multiple fields. The query that i have written is below. Please correct me if i am wrong:
SELECT * FROM bpi_registration
INNER JOIN bpi_teamProfile
ON bpi_registration.id=bpi_teamProfile.id_student1
AND bpi_registration.id=bpi_teamProfile.id_student2
AND bpi_registration.id=bpi_teamProfile.id_student3
AND bpi_registration.id=bpi_teamProfile.id_student4
AND bpi_registration.id=bpi_teamProfile.id_student5
I am trying to implement search filter in such a way that when someone clicks on Team dropdown then the firstname,lastname,email,city,state,country from bpi_registrationshows up. Below is my PHP code
if (isset($_GET['Team']))
{
$sql="SELECT * FROM bpi_registration
INNER JOIN bpi_teamProfile
ON bpi_registration.id=bpi_teamProfile.id_student1
AND bpi_registration.id=bpi_teamProfile.id_student2
AND bpi_registration.id=bpi_teamProfile.id_student3
AND bpi_registration.id=bpi_teamProfile.id_student4
AND bpi_registration.id=bpi_teamProfile.id_student5"
$userQuery = "{$sql} WHERE bpi_teamProfile.team_name = :team_id";
$user = $db->prepare($userQuery);
$user->execute(['team_id' => $_GET['Team']]);
$selectedUser=$user->fetch(PDO::FETCH_ASSOC);
if(isset($selectedUser))
{
echo '<tr>';
echo '<td>' . $selectedUser['first_name'] . '</td>';
echo '<td>' . $selectedUser['last_name'] . '</td>';
echo '<td>' . $selectedUser['email'] . '</td>';
echo '<td>' . $selectedUser['address_city'] . '</td>';
echo '<td>' . $selectedUser['address_state'] . '</td>';
echo '<td>' . $selectedUser['address_country'] . '</td>';
echo '</tr>';
}
}
The URL looks when we click on team filter looks like this - https://www.example.com/retrieve1.php?Grade=&School=&Team=mary+winners&Students=
However i am not able to get the desired result.
It seems unlikely the student id columns in a given row all map back to the same id (in registration)...or the query would be returning properly. If they are different, do want to 'OR' the join?
SELECT * FROM bpi_registration
INNER JOIN bpi_teamProfile
ON (bpi_registration.id=bpi_teamProfile.id_student1)
OR (bpi_registration.id=bpi_teamProfile.id_student2)
OR (bpi_registration.id=bpi_teamProfile.id_student3)
OR (bpi_registration.id=bpi_teamProfile.id_student4)
OR (bpi_registration.id=bpi_teamProfile.id_student5)

Display Event Date, Name and then List Names who have signed up?! MySQL PHP

Really need help! I know this is easy to do but can't get my mind to switch on. I have a db table called 'Bookings' inside of which is the table columns 'StartDate' 'EventTitle' 'Fornames' 'Surname'
What I want to do is query the db and echo a list of the events by their startdate and title and then next to each one display the names that have booked onto each event.
When i run the following code it shows the StartDate, EventTitle and Forename but repeats this for every entry - I hope this makes sense.
$sql = "SELECT *
FROM Bookings";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_array($result) or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<table>';
echo '<tr>';
echo '<td>' . $row['StartDate'] . '</td>' . '<td>' . $row['EventTitle'] . '</td>'
.'<td>' . $row['Forenames'] . '</td>';
echo '</tr>';
echo '</table>';
}
Try:
$sql = "SELECT StartDate, EventTitle, GROUP_CONCAT(Fornames) as Attendees
FROM Bookings
GROUP BY StartDate, EventTitle";
$result = mysql_query($sql) or die (mysql_error());
echo '<table>';
while($row = mysql_fetch_assoc($result)){
echo '<tr>';
echo '<td>' . $row['StartDate'] . '</td>' . '<td>' . $row['EventTitle'] . '</td>'.'<td>' . $row['Attendees'] . '</td>';
echo '</tr>';
}
echo '</table>';
A couple of notes:
mysql_fetch_array() won't give you the field names in $row, but mysql_fetch_assoc() will.
The code you posted would skip the first row of results
<table> doesn't need to be put in for every row.

Mysql query is producing duplicate data

I have a database set up with one table containing customers, and a second containing calls. When a customer calls in it is logged and saved as a text file to the calls database with the date time and the customer ID that called in.
Customer ID is a foreign key that links to ID in the calls table, one customer can have many calls.
I use the following to get the data from the database
$result = mysql_query(" SELECT * FROM customer LEFT JOIN calllog ON calllog.customID = customer.ID INNER JOIN address ON customer.ID = address.customer_ID WHERE CallStatus= 'Open' ")or die(mysql_error());
A for loop then echoes out all of the results like so:
for ($i = $start; $i < $end; $i++)
{
if ($i == $total_results) { break; }
echo "<tr class='main'>";
echo '<td>' . mysql_result($result, $i, 'First_Name') . '</td>';
echo '<td>' . mysql_result($result, $i, 'Surname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'Company_Name') . '</td>';
echo '<td> <div style="width: 200px">' . nl2br(mysql_result($result, $i,'line_1')) . '</div></td>';
echo '<td>' . mysql_result($result, $i, 'town') . '</td>';
echo '<td>' . mysql_result($result, $i, 'customer.ID') . '</td>';
echo '<td>' . mysql_result($result, $i, 'Telephone') . '</td>';
echo '<td><img src="img\job.jpg" title="New Job"/></td>';
echo '<td><button class= "Call" id="Calllog' . mysql_result($result, $i, 'id') . '"></></ /></a></td>';
echo "</tr>";
echo "<tr>";
echo '<td colspan="13"><div ">' . nl2br(mysql_result($result, $i, 'CallNotes')) . '</div></td>'; //Display notes
echo '<td>' . mysql_result($result, $i, 'CallTime') . '</td>';
echo "</tr>";
}
echo "</table>";
multiple call notes are attached to a single customer however I am getting duplicate customers when they have multiple calls. It will echo out:
Tom
Call log1
Jim
Call log1
Tom
call log 2
I was expecting it to go
Tom
Call Log1
Call log2
Jim
Call log 1.
Add group by clause to your SQL statement
SELECT *
FROM customer
LEFT JOIN calllog ON calllog.customID = customer.ID
INNER JOIN address ON customer.ID = address.customer_ID
WHERE CallStatus= 'Open'
GROUP BY customer.ID
I think your INNER JOIN is the culprit change that to an LEFT JOIN.

how to show specific to mysql database

this is showing all result
but i want to show only if pserialno row is here then it will be show
how can i do this please help me
$result1 = mysql_query("SELECT * FROM workorder where opendate BETWEEN '$a' AND '$b' order by opendate ASC");
while($row = mysql_fetch_array($result1))
{
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['opendate'] . '</td>';
echo '<td>' . $row['number'] . '</td>';
echo '<td>' . $row['pserialno'] . '</td>';
but i want to show only if pserialno row is here then it will be show
Just append your WHERE clause to return only those results where pserialno is not blank.
SELECT * FROM workorder where opendate BETWEEN '$a' AND '$b'
AND pserialno <> ""
ORDER BY opendate ASC

Duplication of results from MYSQL query

Hi I have a a query that produces what I need, however I am getting duplicate rows on the output and cannot figure out why, every line is appearing twice. Any ideas?
$query = "SELECT * FROM orders LEFT JOIN users ON orders.USER_ID = users.USER_ID
LEFT JOIN items ON items.CHECKOUT_ID = orders.CHECKOUT_ID ORDER BY
date_order DESC LIMIT 0,1000";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
$order_id = $row["ORDER_ID"];
$date_order = $row["date_order"];
$date_req = $row["delivery"];
$country = $row["country"];
$firstname = $row["name"];
$lastname = $row["surname"];
$email = $row["email"];
$size = $row["size"];
$total_cost = $row["total_cost"];
echo '<tr><td>' . $order_id . ' </td>' .
'<td>' . $date_order . '</td>' .
'<td>' . $date_req . '</td>' .
'<td>' . $country . ' </td>' .
'<td>' . $firstname . ' </td>' .
'<td>' . $lastname . ' </td>' .
'<td>' . $email . ' </td>' .
'<td>' . $size . ' </td>' .
'<td>€' . number_format($total_cost, 2, '.', '') . ' </td>' .
'<td style="text-align:right"><a href="xxxxxxx_Order_Details_Admin.php?id=' . $order_id . '">More Details</td>' .
'<td style="text-align:right"><a href="xxxxxxxx_Order_Details_print.php?id=' . $order_id . '">Print</td>' .
'</tr>';
Your query should be returning one row for every item in the row. Is this what you are expecting? If you are expecting one row per user or one row per order, then you have the wrong query.
From the fields that you are pulling out, I don't think you want the items. Try this query instead:
SELECT *
FROM orders LEFT JOIN
user
ON orders.USER_ID = users.USER_ID
ORDER BY date_order DESC LIMIT 0,1000
If you are still getting duplicates (or duplicate rows when you are expecting one row per item), then you need to look into the underlying tables to see where the duplicates are coming from.
Change your query to:
SELECT DISTINCT o.ORDER _ID, o.date_order, ...
FROM orders o
LEFT JOIN users u
ON o.USER_ID = u.USER_ID
LEFT JOIN items i
ON i.CHECKOUT_ID = o.CHECKOUT_ID
ORDER BY date_order DESC LIMIT 0,1000
Oh, and always specify which columns you want to return. Using * makes it much more difficult to debug.

Categories