SQL Query duplicating values even using Distinct - php

My query seems to be duplicating the values that are being displayed.
I don't understand why, I have 5 tables
products with an id and category (4 of them), then each category is related to another table where the product_name, price is, then each one of these tables is related to the table called stock, stock is the one where price is.
`
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$conn = mysqli_connect("localhost:3307", "root", "", "db_login");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT products.id, products.category, hygiene.product_name, hygiene.price, stock.quantity
FROM products
LEFT JOIN hygiene ON products.id = hygiene.product_id
LEFT JOIN stock ON hygiene.product_id = stock.item_id
WHERE products.category = 'Hygiene'
UNION
SELECT products.id, products.category, food.product_name, food.price, stock.quantity
FROM products
LEFT JOIN food ON products.id = food.product_id
LEFT JOIN stock ON food.product_id = stock.item_id
WHERE products.category = 'Food'
UNION
SELECT products.id, products.category, toys.product_name, toys.price, stock.quantity
FROM products
LEFT JOIN toys ON products.id = toys.product_id
LEFT JOIN stock ON toys.product_id = stock.item_id
WHERE products.category = 'Toys'
UNION
SELECT products.id, products.category, clothes.product_name, clothes.price, stock.quantity
FROM products
LEFT JOIN clothes ON products.id = clothes.product_id
LEFT JOIN stock ON clothes.product_id = stock.item_id
WHERE products.category = 'Clothes'";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
$product_name = isset($row['product_name']) ? $row['product_name'] : '';
$quantity = isset($row['quantity']) ? $row['quantity'] : '';
$price = isset($row['price']) ? $row['price'] : '';
echo "<tr>";
echo "<form name='update' action='update_stock.php' method='post'>";
echo "<td><input type='text' name='product_name' value='".$row ['product_name']."'></td>";
echo "<td><input type='text' class='stock--update--num' name='quantity' value='".$row['quantity']."'></td>";
echo "<td><input type='text' class='stock--update--num' name='price' value='".$row['price']. "€"."'></td>";
echo "<td><input type='submit' name='update' value='Update'></td>";
echo "</form>";
echo "</tr>";
}
?>
</table>`
I wanted for it to display each item only once with the correct quantity and price.
Other code I tried:
`$conn = mysqli_connect("localhost:3307", "root", "", "db_login");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT products.*, hygiene.product_id, hygiene.product_name, hygiene.price, hygiene.image_path, stock.quantity
FROM products
LEFT JOIN hygiene ON products.id = hygiene.product_id
LEFT JOIN stock ON hygiene.product_id = stock.item_id
WHERE products.category = 'Hygiene'
UNION
SELECT DISTINCT products.*, food.product_id, food.product_name, food.price, food.image_path, stock.quantity
FROM products
LEFT JOIN food ON products.id = food.product_id
LEFT JOIN stock ON food.product_id = stock.item_id
WHERE products.category = 'Food'
UNION
SELECT DISTINCT products.*, toys.product_id, toys.product_name, toys.price, toys.image_path, stock.quantity
FROM products
LEFT JOIN toys ON products.id = toys.product_id
LEFT JOIN stock ON toys.product_id = stock.item_id
WHERE products.category = 'Toys'
UNION
SELECT DISTINCT products.*, clothes.product_id, clothes.product_name, clothes.price, clothes.image_path, stock.quantity
FROM products
LEFT JOIN clothes ON products.id = clothes.product_id
LEFT JOIN stock ON clothes.product_id = stock.item_id
WHERE products.category = 'Clothes'";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<form name='update' action='update_stock.php' method='post'>";
$product_name = isset($row['product_name']) ? $row['product_name'] : '';
$quantity = isset($row['quantity']) ? $row['quantity'] : '';
$price = isset($row['price']) ? $row['price'] : '';
echo "<td><input type='text' name='product_name' value='".$product_name."'></td>";
echo "<td><input type='text' class='stock--update--num' name='quantity' value='".$quantity."'></td>";
echo "<td><input type='text' class='stock--update--num' name='price' value='".$price. "€"."'></td>";
echo "<td><input type='submit' name='update' value='Update'></td>";
echo "</form>";
echo "</tr>";
}`

Wrap all your UNION queries in one single DISTINCT query:
SELECT DISTINCT * FROM(
SELECT...
UNION
SELECT....
UNION
SELECT...
)
But looking at your query closely, you are querying for more columns than you are fetching - I don't think product_ids would make a unique result.

Related

Getting information from multiple using MySQLI and be able to echo results

for the past few hours, I have been trying to find a simple method of while loop echoing information from multiple tables at once. I'd like to say I've not pulled all my hair out looking, but I have.
Here is one mysqli query to get the following fields from CUSTOMER
$tid = $_SESSION['user_id']; // "id" is 1 for example
$query = "SELECT * FROM `CUSTOMER` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
};
Here is another mysqli query to get the following fields from SALE
$query = "SELECT * FROM `SALE` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
};
Could someone possibly show me how I can get both of these tables in one query so that echoing both tables information is possible at the same time instead of separately. I am not fussed how it is done, As long as it gets all from both tables for echoing purpose, that is good.
You can do it by using LEFT JOIN like this.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
And this is your code.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `SALE`.user_id=`CUSTOMER`.user_id WHERE `SALE`.user_id={$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
}
For more info read this,
https://www.w3schools.com/sql/sql_join_left.asp
I hope this helps.
EDITED
This is for joining 3 tables,
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
LEFT JOIN table3 ON table1.column_name = table3.column_name;
In your code.
SELECT * FROM `CUSTOMER`
LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id
LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id
WHERE `SALE`.user_id={$tid};
As variable.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id WHERE `SALE`.user_id={$tid}";
You can use the following code and will help u solve Ur problem
$query = "SELECT C.*,S.* FROM CUSTOMER C,SALES S
WHERE C.user_id={$tid}
and C.user_id=S.user_id;
while ($row = mysqli_fetch_array($results)) {
echo $row['C.user_id'] . "<br><br>";
echo $row['C.c_fname'] . "<br>";
echo $row['C.c_sname'] . "<br>";
echo $row['S.s_date'] . "<br>";
echo $row['S.s_total'] . "<br>";
};
You can simply join the tables to get your expected result as shown below.
$query = "SELECT c.user_id, c.c_fname, c.c_sname, s.s_date, s.s_total FROM `CUSTOMER` AS c INNER JOIN `SALE` AS s ON c.user_id = s.user_id WHERE c.user_id = {$tid}";
Joining 3 tables example
$query = "SELECT *
FROM `CUSTOMER` AS c
INNER JOIN `SALE` AS s ON c.user_id = s.user_id
INNER JOIN `PRODUCTS` AS p ON p.product_id = s.product_id
WHERE c.user_id = {$tid}";

Group by is not showing all the rows

I am working in WordPress and below is my select query. I have used leftjoin and group by. But only one row is returned if I have duplicate entries in my articles.username coloumn. So I want all the rows to be returned with group by and duplicates should be allowed in username field.
PHP Code
$sqll = "SELECT articles.aid, articles.username, articles.competition, articles.path, articles.category, articles.title, Sum(zvotes.zvotes) AS votessum FROM articles LEFT JOIN zvotes on articles.aid=zvotes.aid GROUP BY articles.competition HAVING articles.category = '$cat' && articles.competition = '$comp' ORDER BY votessum";
$results = $wpdb->get_results($wpdb->prepare($sqll)) or die(mysql_error());
Snapshot of articles table
Snapshot of votes table (currently no data in it)
Below is my full code
echo '<form action="" method="post">';
echo '<select name="category" id="category" style="width:250px; background-color:lightgrey;">';
echo '<option value="" disabled="disabled" selected="selected" ">Select category</option>';
echo '<option value="My Testimony">My Testimony</option>';
echo '<option value="Love & Relationships">Love & Relationships</option>';
echo '<option value="Miscellaneous">Miscellaneous</option>';
echo '</select>';
echo '<input type="submit" name="a" value="Search" style="margin-left:15px; margin-bottom:15px;">';
echo '</form>';
//show after drop down value is selected
if(isset($_POST['a'])){
//echo "zeeshanaslamdurrani". "<br>";
echo do_shortcode('[ujicountdown id="Photos Contest" expire="2015/04/30 00:00" hide="true" url="" subscr="sdf" recurring="" rectype="second" repeats=""]');
global $wpdb;
//get current competition value
$cat =$_POST['category'];
$comp = $wpdb->get_var("SELECT competition FROM competition ORDER BY cid DESC LIMIT 1");
//echo $comp;
$sql = "SELECT * FROM articles WHERE category='$cat'";
$comp = $wpdb->get_var("SELECT competition FROM competition ORDER BY cid DESC LIMIT 1");
echo "current competition is ". $comp;
//test query
$sqll = "SELECT articles.aid, articles.username, articles.competition, articles.path, articles.category, articles.title, Sum(zvotes.zvotes) AS votessum FROM articles LEFT JOIN zvotes on articles.aid=zvotes.aid GROUP BY articles.competition HAVING articles.category = '$cat' && articles.competition = '$comp' ORDER BY votessum";
$results = $wpdb->get_results($wpdb->prepare($sqll)) or die(mysql_error());
foreach( $results as $result ) {
echo '<form action="" method="post">';
echo "<input name='category' type='hidden' value='$result->category'>";
echo $result->title.'<br>';
echo "<img src='$result->path' width='150' height='150' >" . '<br><br>';
echo $result->body.'<br>';
echo "<input name='comp' type='hidden' value='$result->competition'>";
echo $result->username.'<br>';
echo $result->votessum.'<br>';
echo "<input style='margin-bottom:30px;' value='vote' name='submit' type='submit'/></form>";
}//end of foreach
}//end of isset
I have a drop down on the top of the page and a search button as shown below on pressing search the results are shown but if I add duplicate values in username field of articles table I get only 1 row in result.
My page
If you want to show each user, then I think you should be aggregating by the user. In fact, you should be aggregating by every column in the SELECT that is not an argument to an aggregation function.
This may do what you want:
SELECT a.aid, a.username, a.competition, a.path, a.category, a.title,
Sum(z.zvotes) AS votessum
FROM articles a LEFT JOIN
zvotes z
on a.aid = z.aid
WHERE a.category = '$cat' AND a.competition = '$comp'
GROUP BY a.aid, a.username, a.competition, a.path, a.category, a.title
ORDER BY votessum";

2 columns on a left join

Hello so I have 2 tables. tbl_records and tbl_guards. On tbl_guards I have guard_id and on tbl_records I have guard_id and guard_id_in. And here is my current code:
try
{
$stat = "0";
$query = "SELECT rec.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records as rec
LEFT JOIN tbl_guard ON tbl_guard.guard_id = rec.guard_id
LEFT JOIN tbl_records ON tbl_records.guard_id_in = tbl_guard.guard_id
WHERE rec.stud_id=? AND rec.status=?";
$stmt = $dbc->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$stmt->bindParam(2, $stat);
$stmt->execute();
echo "<table cellpadding='3' class='searchTbl'>";
echo "<thead>";
echo "<tr>";
echo "<th>Actual Date</th>";
echo "<th>Purpose</th>";
echo "<th>Destination</th>";
echo "<th>Exact TO</th>";
echo "<th>Expected TI</th>";
echo "<th>Guard</th>";
echo "<th>Actual TI</th>";
echo "<th>Guard IN</th>";
echo "</tr>";
echo "</thead>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$guard = $fname . " " . $lname;
echo "<tbody>";
echo "<tr>";
echo "<td>$act_date</td>";
echo "<td>$purpose</td>";
echo "<td>$destination</td>";
echo "<td>$exact_timeout</td>";
echo "<td>$exp_timein</td>";
echo "<td>$guard</td>";
echo "<td>$act_timein</td>";
echo "<td>$guard</td>";
echo "</tr>";
echo "</tbody>";
}
}
catch (PDOException $e)
{
echo "Error: " . $e->getMessage();
}
echo "</table>";
Here is tbl_records data.
And here is tbl_guard data.
Here is the current output.
My problem is it shows the same guard in guard_id and guard_id_in in my code.
You can use LEFT JOIN multiple times, like:
SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records as rec
LEFT JOIN tbl_guard ON tbl_guard.guard_id = rec.guard_id
LEFT JOIN tbl_records ON tbl_records.guard_id_in = tbl_guard.guard_id
You can use:
SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname
FROM tbl_records
LEFT JOIN tbl_guard ON (tbl_records.guard_id OR tbl_records.guard_id_in) = tbl_guard.guard_id
You should select twice the guard table and use aliases for your fields :
SELECT tr1.*, tg1.fname AS FNAME, tg1.lname AS LNAME,
tg2.fname AS FNAME_IN, tg2.lname AS LNAME_IN
FROM tbl_records AS tr1
LEFT JOIN tbl_guard AS tg1
ON tg1.guard_id = tr1.guard_id,
LEFT JOIN tbl_guard AS tg2
ON tg2.guard_id = trl.guard_id_in
then in PHP you'll have more vars : $FNAME, $LNAME, $FNAME_IN, $LNAME_IN
Just to be sure, your tbl_records table can have a link to two different tbl_guards via guard_id and guard_id_in ?
Maybe you can try :
SELECT tbl_records.*, tbl_guard.fname, tbl_guard.lname FROM tbl_records LEFT JOIN tbl_guard ON tbl_guard.guard_id IN (tbl_records.guard_id, tbl_records.guard_id_in)
SELECT tr1.*, tg1.fname, tg2.lname
FROM tbl_records AS tr1
LEFT JOIN tbl_guard AS tg1 ON tg1.guard_id = tr1.guard_id,
LEFT JOIN tbl_guard AS tg2 ON tg2.guard_id = trl.guard_id_in

how to repeat entire table in while loop

I have a code which repeats rows while loop, but how can i repeat the entire table in while loop.
The code is
$kandivli = mysql_query("SELECT ps_order_detail.product_name, sum(ps_order_detail.product_quantity) AS product_total FROM ps_order_detail JOIN ps_product ON ps_product.id_product = ps_order_detail.product_id JOIN ps_orders ON ps_orders.id_order = ps_order_detail.id_order WHERE ps_product.id_supplier = '" . $supplier_number . "' && ps_orders.current_state = '" . $status1 ."' && ps_order_detail.id_shop = 1 GROUP BY ps_order_detail.product_name");
$ktotal = mysql_query("SELECT sum(ps_order_detail.product_quantity) AS product_total FROM ps_order_detail JOIN ps_product ON ps_product.id_product = ps_order_detail.product_id JOIN ps_orders ON ps_orders.id_order = ps_order_detail.id_order WHERE ps_product.id_supplier = '" . $supplier_number . "' && ps_orders.current_state = '" . $status1 ."' && ps_order_detail.id_shop = 1");
$krow = mysql_fetch_array($ktotal);
$kftotal = $krow['product_total'];
if(mysql_num_rows($kandivli) > 0)
{
echo '<table border="1" align="center" class="total">';
echo "<th> Product Name </td><th> Total Quantity </th>";
while($kandivlirow = mysql_fetch_array($kandivli))
{
$kandivli_product = $kandivlirow['product_name'];
$kandivlitotal = $kandivlirow['product_total'];
echo '<tr>';
echo "<td align='center'>$kandivli_product</td><tdalign='center'>$kandivlitotal</td>";
echo '</tr>';
}
echo "<td align='center'><b>Total</b></td><td align='center'><b>$kftotal</b></td>";
echo '</table>';
}
else echo "<div align='center'>No Pending orders</div>";
?>
Right now i just have 5 shops but if i add a new shop every time i have to copy paste and change this code to && ps_order_detail.id_shop = 6 then && ps_order_detail.id_shop = 7 and so on
So please if anyone shows how to repeat table. It would be grateful.
Hope my question is clear. (I want to repeat the entire table)
Regards
Amod
Ok I have Edited the code Now i get 6 tables as expected but the rows show the same data of shop one.
<?php
session_start();
include_once "connect.php";
?>
<?php
$supplier = mysql_query("SELECT ps_order_detail.product_name, sum(ps_order_detail.product_quantity) AS product_total, ps_supplier.name FROM ps_order_detail JOIN ps_product ON ps_product.id_product = ps_order_detail.product_id JOIN ps_supplier ON ps_supplier.id_supplier = ps_product.id_supplier JOIN ps_orders ON ps_orders.id_order = ps_order_detail.id_order WHERE ps_orders.current_state = 4 GROUP BY ps_order_detail.id_shop");
$alltotal = mysql_query("SELECT sum(ps_order_detail.product_quantity) AS producttotal FROM ps_order_detail JOIN ps_product ON ps_product.id_product = ps_order_detail.product_id JOIN ps_orders ON ps_orders.id_order = ps_order_detail.id_order WHERE ps_orders.current_state = 4 && ps_order_detail.id_shop = 11");
$ct = mysql_fetch_array($alltotal);
$ct1 = $ct['producttotal'];
while($supplierrow = mysql_fetch_array($supplier))
{
$kandivli = mysql_query("SELECT ps_order_detail.product_name, sum(ps_order_detail.product_quantity) AS product_total,ps_supplier.name FROM ps_order_detail JOIN ps_product ON ps_product.id_product = ps_order_detail.product_id JOIN ps_supplier ON ps_supplier.id_supplier = ps_product.id_supplier JOIN ps_orders ON ps_orders.id_order = ps_order_detail.id_order WHERE ps_orders.current_state = 4 GROUP BY ps_order_detail.product_name");
echo '<table border="1" align="center" class="total">';
while($kandivlirow = mysql_fetch_array($kandivli))
{
$sup = $kandivlirow['name'];
$sp = $kandivlirow['product_name'];
$spt = $kadivlirow['product_total'];
echo '<tr>';
echo "<td align='center'>$sp</td><td align='center'>$spt</td><td align='center'>$sup</td>";
echo '</tr>';
}
echo '</table>';
echo '<br>';
}
echo "<td align='center'><b>Total</b></td><td align='center'><b>$ct1</b></td>";
?>
while($kandivlirow = mysql_fetch_array($kandivli))
{
//Your table code
echo '<table border="1" align="center" class="total">';
//Middle section
echo '</table>';
}

give page user control over where condition

Hi im new to php and have very little knowledge, in my where statement I have where Status='A' and z.zoneID=1, is there a way to give the page user control over the z.zoneID=1 so that they can change it to any zoneID that is available, maybe through a drop-down list?
////////Query & Data Display is here/////////
$q=mysql_query("select r.*, f.Functionname, m.Managername, z.Zonename from requests as r inner join functions as f on r.functionID = f.functionID inner join managers as m on r.managerID = m.managerID inner join zones as z on r.zoneID = z.zoneID where Status='A' and z.zoneID=1 order by Functionname");
echo "<table>
<tr>
<th>Function</th>
<th>Manager</th>
</tr>"
;
while($nt=mysql_fetch_array($q)){
echo"<b>Zone: $nt[Zonename]<br>Capacity: $nt[Zonecapacity]</b><br><br>";
echo "<tr><td>$nt[Functionname]</td><td>$nt[Managername]</td></tr>";
}
echo "</table>";
/////////////////////////////////////
This can help you out...
if( isset($_POST['zoneid']) ){
$zoneID = $_POST['zoneid'];
//Your extra code or processing here.
}
$q=mysql_query("select r.*, f.Functionname, m.Managername, z.Zonename from requests as r inner join functions as f on r.functionID = f.functionID inner join managers as m on r.managerID = m.managerID inner join zones as z on r.zoneID = z.zoneID where Status='A' and z.zoneID=1 order by Functionname");
echo "<table>
<tr>
<th>Function</th>
<th>Manager</th>
</tr>"
;
// Here we create a form
echo "<form method='post' >";
echo "<Search for ZoneID: <input type='number' name='zoneid' /><br>";
echo "<input type='submit' value='search' />";
echo "</form>";
while($nt=mysql_fetch_array($q)){
echo"<b>Zone: ".$nt['Zonename']."<br>Capacity: ".$nt['Zonecapacity']."</b><br><br>";
echo "<tr><td>$nt[Functionname]</td><td>$nt[Managername]</td></tr>";
}
echo "</table>";
?>

Categories