Duplication of results from MYSQL query - php

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.

Related

While doesnt give me more trainers

I'm trying to make a map with available gyms that also shows what exercises they have. So it looks like this:
Name Gym
Open spots: (number)
Logo image of Gym
Time of excercise.
Image of a dumbel for example
Trainer
The part from Time of exercise til Trainer needs to show more than one, I got like 6 exercises with 6 trainers, and 6 times and 6 different images of exercises to show. I store those in a database; but they don't show up.
Here my code:
$sql = "SELECT * FROM forts";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
echo "[";
$output = array();
while($row = $result->fetch_assoc()) {
$url = preg_replace("/^http:/i", "https:", $row['url']);
$sqlmon = "SELECT * FROM gym_trainers WHERE fort_id = " . $row['id'];
$resultmon = $mysqli->query($sqlmon);
$mon = $resultmon->fetch_assoc();
$sqlextra = "SELECT * FROM extrainfo WHERE fort_id = " . $row['id'] . " ORDER BY last_modified DESC";
$resultextra = $mysqli->query($sqlextra);
$extra = $resultextra->fetch_assoc();
array_push($output, '
{
"id": "' . $row['id'] . '",
"name": "' . htmlspecialchars($row['name']) . '",
"image": "' . $url . '",
"team": "' . $team . '",
"spots": ' . $extra['spots'] . ',
"exer_time": ' . $mon['time_exerise'] . ',
"trainer": "' . htmlspecialchars($mon['trainer_name']) . '",
"exercise_id": ' . $mon['exercise_id'] . ',
"lat": ' . $row['lat'] . ',
"lng": ' . $row['lon'] . '
}
');
}
echo implode(",", $output);
echo "]";
I think something with this part needs to change, but don't know what:
"exer_time": ' . $mon['time_exerise'] . ',
"trainer": "' . htmlspecialchars($mon['trainer_name']) . '",
"exercise_id": ' . $mon['exercise_id'] . ',
The specific problem is that you fetch only 1 record from the gym_trainers table (the $resultmon->fetch_assoc() is not in a separate loop).
The wider problem is that you do not use joins. The 3 separate sql queries could be written as
select *
from forts f
left join gym_trainers g on f.id=g.fort_id
left join extrainfo e on f.id=g.fort_id
In this case you would need a single loop and within the single loop you track if the fort changes.

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 display the whole table of my job including their categories that I had to create from mySQL Workbench to php?

This is my php code for displaying the table from mySQL workbench:
$stmt = $pdo->prepare(' SELECT jobs.*, categories.category_name
FROM jobs
LEFT JOIN vacancies.categories ON categories.category_id = jobs.category_id
WHERE jobs.category_id =:category_id');
$choice = 0;// just a temp for test
$criteria = [
'category_id' => $choice,
];
$stmt -> execute($criteria);
while ($row = $stmt->fetch()){
echo '<br>' . $row['id']. ' ' . $row['title']. ' ' . $row['salary']. ' ' . $row['location']. ' ' . $row['description']. '<br> category is:'.$row['category_name'].'</br>';
}
Now if I run this and check my webpage it only shows the jobs that hve the category_id of the $choice I put but I want to display all of the job table.
I have a category table with 6 categories (0 is the start) and in my other table that is called jobs. I have 7 jobs with their details.
I hope someone understand what I am trying to say and can help me out. Ask me anything if I don't give out enough.
You are using a prepared query to norrow the results to a defined criteria. If you want to display all the jobs you should simply remove the WHERE tag and use a simple query
$stmt = $pdo->query(' SELECT jobs.*, categories.category_name
FROM jobs
LEFT JOIN vacancies.categories ON categories.category_id = jobs.category_id');
echo '<table>';
while ($row = $stmt->fetch()){
echo '<tr><td>' . $row['id']. '</td><td>' . $row['title']. '</td><td>' . $row['salary']. '</td><td>' . $row['location']. '</td><td>' . $row['description'].'</td><td> category is:'.$row['category_name'].'</td></tr>';
}
echo '</table>';

Displaying Expenses under each expense type using MySQL PDO

I have two tables that I am creating a list that shows all the expenses under each expense type. I have been able to get it to work except when I add the
AND WHERE expenses.pid = " . $pid
it cases a Syntax error and I can't figure out way.
The biggest thing is I need to limet the Expense Type to only show the ones that have some data to go below them
EXPENSETYPE
typeid
pid
exptype
EXPENSES
expid
pid
expdate
checktype
payee
typeid
details
amount
<?php
$pid = 6;
$sql = "SELECT expensetype.typeid, expensetype.exptype
FROM `expensetype` WHERE expensetype.pid = $pid
ORDER BY expensetype.typeid DESC";
$expensetype = $db->query($sql);
foreach($expensetype as $type) {
echo '<li>' . $type['exptype'] . '<ul>';
$sql2 = "SELECT expenses.expid, expenses.expdate, expenses.checktype, expenses.payee, expenses.details, expenses.amount
FROM `expenses` WHERE `expenses`.typeid = " . $type['typeid'] . "AND WHERE expenses.pid = " . $pid ;
$expenses = $db->query($sql2);
foreach($expenses as $exp) {
echo '<li>' . $exp['expdate'] . ' ' . $exp['checktype'] . ' ' . $exp['expdate'] . ' ' . $exp['payee'] . ' ' . $exp['details'] .' ' . $exp['amount'] .'</li>';
}
echo '</ul></li>';
}
?>
Try this SQL statement instead of making two of them :
SELECT `expensetype`.`typeid`, `expensetype.exptype`, `expenses`.`expid`,
`expenses`.`expdate`, `expenses`.`checktype`, `expenses`.`payee`,
`expenses`.`details`, `expenses`.`amount`
FROM `expensetype` INNER JOIN `expenses` ON
`expensetype`.`typeid` = `expense`.`typeid`
WHERE (...)
Also, you cannot use two WHERE in a SQL statement, only use AND.

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