Ordering Logs of checkouts echoed from database by date - php

So i have to have a page where all of the logs from another one of our pages is echoed out.
$query = "SELECT * FROM `returnform` WHERE department_id=1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<tr class='divEnglish'> <td>" . $row['name'] . "</td>" . " " . "<td>" . $row['returned_date'] . "</td>" . " " . "<td>" . $row['lost'] . "</td>" . " " . "<td>" . $row['lossnum'] . "</td>" . " " . "<td>" . $row['putback'] . "</td>","</tr>";
};
I need all of the rows echoed out to be put in order from newest to oldest so that when people view the page the latest logs.

You need to add order by clause into your query.
$query = "SELECT * FROM `returnform` WHERE department_id=1 ORDER BY create_date DESC";
I suppose you have date, when to record was created, the column name is create_date.

Related

Trying to join different table from different database in the localhost, Used MYSQL

Explanations:
First of all im new in the database field, i got system from my boss, my boss ask me to create dashboard based on the data from database, but some data need to join other table in different database. In my case i need to fetch data at column score from table rank in 4 different database which is "virtualexam, virtualexam1, virtualexam2, virtualexam3,"
. I had try and search but i cant display the data into the table, your advice and recommendation really appreciate it.. Thank you for you kindness
Error picture
click here
Database Table Picture *Dummy data
db.virtualexam
db.virtualexam1
db.virtualexam2
db,virtualexam3
my query
<?php
$sql = "SELECT virtualexam.rank.id, virtualexam.rank.username,
virtualexam.rank.score AS score, virtualexam1.rank.score AS 'score1', virtualexam2.rank.score AS 'score2', virtualexam3.rank.score AS 'score3'
SUM(virtualexam.rank.score + virtualexam1.rank.score + virtualexam2.rank.score + virtualexam3.rank.score ) AS 'total'
FROM virtualexam.rank
JOIN virtualexam1.rank ON virtualexam.rank.username = virtualexam1.rank.username,
JOIN virtualexam2.rank ON virtualexam1.rank.username = virtualexam2.rank.username,
JOIN virtualexam3.rank ON virtualexam2.rank.username = virtualexam3.rank.username
GROUP BY id ";
$result = $conn->query($sql);
?>
display in the table
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "<td>" . $row['score1'] . "</td>";
echo "<td>" . $row['score2'] . "</td>";
echo "<td>" . $row['score3'] . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>";
}
?>
</tbody>
$sql = "SELECT virtualexam.rank.id, virtualexam.rank.username,
virtualexam.rank.score AS score, virtualexam1.rank.score AS 'score1', virtualexam2.rank.score AS 'score2', virtualexam3.rank.score AS 'score3',
SUM(virtualexam.rank.score + virtualexam1.rank.score + virtualexam2.rank.score + virtualexam3.rank.score ) AS 'total'
FROM virtualexam.rank
JOIN virtualexam1.rank ON (virtualexam.rank.username = virtualexam1.rank.username)
JOIN virtualexam2.rank ON (virtualexam2.rank.username = virtualexam1.rank.username)
JOIN virtualexam3.rank ON (virtualexam3.rank.username = virtualexam2.rank.username)
GROUP BY virtualexam.rank.username";

PHP Change MySQL Order By If Condition Met

I'm trying to change the order of MySQL results depending on if an if condition is met in PHP.
My code checks to see if any rows are duplicates and changes the row class if it is.
What I'm trying to achieve is if there is a duplicate then the MySQL query is ordered by Frequency and if there are no duplicates found then order it by Name.
This is what I have:
function getFrequencies() {
$conn = getConnected("websiteData");
$frequencyQuery = "
SELECT
f.Name,
f.Frequency,
f.Country,
f.Programmed,
(SELECT count(*) FROM frequencies WHERE Frequency = f.Frequency) as count
FROM frequencies f;
";
$frequencyResult = mysqli_query($conn, $frequencyQuery);
while ($frequencyRow = mysqli_fetch_assoc($frequencyResult)) {
if($frequencyRow['count'] > 1) {
$frequencyQuery = "
SELECT
f.Name,
f.Frequency,
f.Country,
f.Programmed,
(SELECT count(*) FROM frequencies WHERE Frequency = f.Frequency) as count
FROM frequencies f
ORDER BY Frequency;
";
} else {
$frequencyQuery = "
SELECT
Name,
Frequency,
Country,
Programmed
FROM frequencies
ORDER BY Name;
";
}
}
$frequencyResult = mysqli_query($conn, $frequencyQuery);
while ($frequencyRow = mysqli_fetch_assoc($frequencyResult)){
if ($frequencyRow['count'] > 1) {
echo '<tr class="warning">' .
"<td>" . $frequencyRow['Name'] . "</td>" .
"<td>" . $frequencyRow['Frequency'] . "</td>" .
"<td>" . $frequencyRow['Country'] . "</td>" .
"<td>" . $frequencyRow['Programmed'] . "</td>" .
"</tr>" . PHP_EOL;
} else {
echo "<tr>" . PHP_EOL .
"<td>" . $frequencyRow['Name'] . "</td>" .
"<td>" . $frequencyRow['Frequency'] . "</td>" .
"<td>" . $frequencyRow['Country'] . "</td>" .
"<td>" . $frequencyRow['Programmed'] . "</td>" .
"</tr>" . PHP_EOL;
}
}
}
Now I know for a fact that my table contains duplicates but currently there aren't any highlighted rows and the order is by Name.
Before I changed my code to the above stated one it was this one which did highlight my duplicate rows:
function getFrequencies() {
$conn = getConnected("websiteData");
// $frequencyQuery = "SELECT Name, Frequency, Country, Programmed, count(*) FROM frequencies GROUP BY Frequency ORDER BY Name";
$frequencyQuery = "
SELECT
f.Name,
f.Frequency,
f.Country,
f.Programmed,
( SELECT count(*) FROM frequencies WHERE Frequency = f.Frequency ) as count
FROM frequencies f
ORDER BY Frequency;
";
$frequencyResult = mysqli_query($conn, $frequencyQuery);
while ($frequencyRow = mysqli_fetch_assoc($frequencyResult)) {
if ($frequencyRow['count'] > 1) {
echo '<tr class="danger">' . PHP_EOL .
"<td>" . $frequencyRow['Name'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Frequency'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Country'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Programmed'] . "</td>" . PHP_EOL .
"</tr>" . PHP_EOL;
} else {
echo "<tr>" . PHP_EOL .
"<td>" . $frequencyRow['Name'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Frequency'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Country'] . "</td>" . PHP_EOL .
"<td>" . $frequencyRow['Programmed'] . "</td>" . PHP_EOL .
"</tr>" . PHP_EOL;
}
}
}
What can I do to achieve what I am trying to do? The reason I want to change the order is because when there are no duplicates it is a preference to scroll through the list alphabetically, but if there are duplicates then ordering it by Frequency puts the duplicates one row after the other making it easy to find and edit/delete.
Based on what you're trying to do I would build an Associative Array of the results and then use your logic to order them using PHP instead of MySQL's order by clause.
A method you could take (if you want to retain all duplicates) would be to build the table by sorting the array by the Name key and then saying if unique display else for each duplicate in array display which will result in all of the duplicates being displayed in succession, with the entire thing sorted by Name alphabetically, you can use asort for this.
In order to stop this from triggering side effects you could build two arrays, one from the MySQL select and one that is unique using array_unique that way when you loop through the array to display the page you can loop through the unique array and only grab the duplicate elements from the original array when rendering.
Consider the following:
<?php
$array = array();
$uniqueArray = array_unique($array);
for ( $i = 0; $i < sizeof($uniqueArray); ++$i ) {
if ( in_array($uniqueArray[$i], $array) ) {
// Item has duplicates
} else {
// item is unique
}
}
?>
If you don't want to retain duplicates you can quite simply follow the same formula but upon matching a duplicate instead of displaying them you can purge each of them from the database only retaining one then render the item from the unique array.

how to pull up the last entry of each product

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;

How to create a foreach that has 2 or more conditions in PHP with Codeigniter?

Hi how do I create a 2 foreach loop in php? I wanted to result the query with the Codeigniter format. But I'm having problem with the foreach loop here's the code for the query.
$query = $this -> db -> query("SELECT * FROM CUSTOMERS where CUSTOMER_ID IN (SELECT Customer_ID from Orders)");
$resultOrder = $this -> db -> query ("SELECT * FROM orders");
And I wanted to output this
foreach (array_merge($resultOrder->result(),$query->result()) as $row )
{
echo "<tr>";
echo "<td>" . $row -> Order_ID . "</td>";
echo "<td>" . $row -> First_Name . " " . $row ->Last_Name . "</td>";
echo "<td>" . $row-> Order_Date . "</td>";
echo "<td>" . $row->Delivery_Date . "</td>";
echo "<td>" . $row -> Status . "</td>";
echo "<td>" . $row ->Remarks . "</td>";
echo "</tr>";
}
But it has error. It says
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$First_Name
Filename: xxxx/xxxxxx.php
Line Number: xx
Thanks!
Edit:
Apparently it has an output but the output of $row -> First_Name . " " . $row ->Last_Name is separated to the others
Try a SQL join like this
SELECT * FROM CUSTOMERS c
left join orders o on o.customer_id = c.customer_id
where CUSTOMER_ID IN (SELECT Customer_ID from Orders)

Multiple While Loops within a While Loop?

Total newbie trying to learn... thanks for all the help so far!
UPDATE - updated code below - Thanks Phill
I'm now trying to get the relevant horse information from a table horses which I can join to race_form with the horse_name field. I want to then display the information for each horse in the race below the while($racecard) info. Does this make it a bit clearer?
I thought I could just do another query and then a while loop with mysql_fetch_array below the one I have already and that would display it and then move onto the next race, but that apparently doesn't work...?!
I'm wondering if you can run 2 while loops after each other inside a while loop? I am working on a horse racing formguide - I can display each race list, but underneath I want to display individual horse details on each horse in the race. Anyway if you look at this page you can see what I'm trying to do:
http://tasmanianracing.com/superform/formguide.php?meetingID=21042011LAUN&Submit=View+Form
Problem is, any time I put a second while loop after the race list, it won't show up. I'm trying to run a query to get the horse details from my horse table and then run a while for each horse in the race, but nothing shows up.
I hope this is clear enough ... my snippet of code is below - please let me know if I've missed out something important:
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $row['race_number'] . " at " . $row['start_time'] . " " . $row['class'] . " over " . $row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $row['raceID'] . "')");
while($row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $row['number'] . "</td><td>" . $row['past10'] . "</td><td>" . $row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
echo "</table>";
You'll probably need to change the names of some of the $row variables, they may interfere with each other.
For example:
while($row_races = mysql_fetch_array($totalraces)){
while($row_details = mysql_fetch_array($racedetails)){
while($row_card = mysql_fetch_array($racecard)){
I think you can get rid of one of your queries:
The first query gets the number of races by selecting a COUNT, This returns one record with the count value.
// This returns one record with the count
$total_races = "SELECT COUNT(race_number) AS totalraces
FROM race_info WHERE meetingID = ('".$safemeetingID."') ";
Next you iterate over the the same records as the rows returned for the race details are the same as the count.
// This looks to return the record(s) with the race details
$race_details = "SELECT * FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')";
I think you can just use this to get the desired results: (I agree to rename the $row variable(s) to something descriptive for each while loop)
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
NOT TESTED/PSEUDO CODE
"SELECT *
FROM horses AS h,
INNER JOIN race_info AS ri ON race_form.raceID = race_info.raceID
WHERE horse_name IN (
SELECT horse_name
FROM race_form AS srf
WHERE h.horse_name = srf.horse_name
)
AND race_form.raceID = ('" . $details_row['raceID'] . "')"
The idea is to join the two queries into one, I know this is not the correct syntax but it might give you an idea on how to go about it.
Or you can do another query while loop for the horse names
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
$horses = mysql_query("SELECT *
FROM horses
WHERE horse_name = ('" . $rc_row['horse_name'] . "')");
while($horse_row = mysql_fetch_array($horses))
{
// echo horse details here
}
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
I theory you could and in practice you can, but a while in a while in a for in a while seems a little bit over the top...
I'm sure we can help you make it more efficient if you explain what it is you're trying to do.

Categories