I have managed to create a JOIN query for three tables and can successfully echo out the results in a echoed table, here is my code:
<?php
$sql="SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
ORDER BY product_name DESC";
$result = mysql_query($sql);
if (!$result)
{
echo "An error occurred ".mysql_error();
exit;
}
echo "<table border=1>\n<tr><th></th><th bgcolor=\"#DFE8EC\">Name</th><th>Flavors & Size</th><th bgcolor=\"#DFE8EC\">Price</th><th>Price Difference</th><th bgcolor=\"#DFE8EC\"></th></tr>\n";
while ($line = mysql_fetch_array($result)) {
$name = $line["product_name"];
$price = $line["product_price"];
$options=$line["Options_name"];
$difference=$line["Price_diff"];
echo "<tr><td></td><td bgcolor=\"#DFE8EC\">$name</td><td>$options</td> <td bgcolor=\"#DFE8EC\">£$price</td><td>£$difference</td><td bgcolor=\"#DFE8EC\"></td></tr>\n";
}
echo "</table>\n";
?>
My table works but it shows duplicate entries for product_name and I do not know how to remove them.
You have to use a GROUP BY clause in your query like this:
$sql = "SELECT a.product_id, a.Options_id, b.product_name, b.product_price, c.Options_name, c.Price_diff
FROM ProductOptions a
JOIN Products b ON a.product_id = b.product_id
JOIN Options c ON a.Options_id = c.Options_id
GROUP BY product_name
ORDER BY product_name DESC";
Related
I have 4 tables:
clients, pricelist, result and result_details
I want to generate a form where the transaction_id, name, test_name and result appear on it. I have done a select for the name but I can't figure out a select for the test_name and result.
I want something like this [pdf][5]
$result=mysqli_query($con,"SELECT r.transaction_Id,r.client_id,r.result_id,r.test_id,t.test_id,t.result,p.test_id,p.Name,c.Id,c.surName,c.firstName,c.dob,c.Gender FROM result r
JOIN result_details t
on r.test_id = t.test_id
left JOIN pricelist p ON r.test_id = p.test_id
left JOIN clients c ON r.client_id = c.Id")or die(mysqli_error());
$r=mysqli_query($con,"SELECT DISTINCT id,firstName,surName,Gender,dob FROM clients join result WHERE result.client_id=clients.Id")or die(mysqli_error());
while ($row = mysqli_fetch_array ($r)) {
$id=$row['id'];
$clientfirstname=$row['firstName'];
$surname=$row['surName'];
$gender=$row['Gender'];
$dob=$row['dob'];
$t=mysqli_query($con,"SELECT transaction_Id FROM transaction WHERE clientId=$id") or die(mysqli_error());
while ($test = mysqli_fetch_array ($t)) {
$transaction=$test['transaction_Id'];
$m=mysqli_query($con,"SELECT test_id,result_id from result where client_id=$id")or die(mysqli_error());
while ($q = mysqli_fetch_array ($m)) {
$test_id=$q['test_id'];
$result_id=$q['result_id'];
$z=mysqli_query($con,"SELECT Name from pricelist where test_id=$test_id")or die(mysqli_error());
while ($x = mysqli_fetch_array ($z)) {
$name=$x['Name'];
$query=mysqli_query($con,"SELECT result from result_details where result_id=$result_id")or die(mysqli_error());
while ($query1 = mysqli_fetch_array ($query)) {
$result=$query1['result'];
}
}
}
}
}
Just add:
GROUP BY AcctNo, OrderDate, Charge
HAVING COUNT(1) = 1
The GROUP BY groups all rows with the same field1, field2, ... and Charge together, then the HAVING COUNT(1) = 1 shows only the rows where there was just 1 progenitor. I hope it will work
Need help getting a sum for quantity and accessory_price in my current query to display in my table.
Here is my query:
$query = ('SELECT accessories.accessory_name,accessory_only_solds.transaction_id,accessory_only_solds.quantity,accessory_only_solds.accessory_price,transactions.date_purchased, FROM accessory_only_solds
left join accessories on accessory_only_solds.accessory_id = accessories.id
left join transactions on transactions.id = accessory_only_solds.transaction_id
ORDER BY transactions.date_purchased DESC');
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['date_purchased']), htmlspecialchars($myrow['accessory_name']), htmlspecialchars($myrow['accessory_price']), htmlspecialchars($myrow['quantity']), number_format($myrow['**sumhere**'], 2));
}
I tried adding this to my query but keep getting server error
TO_CHAR(CAST(accessory_only_solds.accessory_price AS NUMERIC)* accessory_only_solds.quantity),'999,999.99') AS atotal
!!!was able to solve my problem though i still need to convert the value to euro currency format.
$query = ('SELECT accessories.accessory_name,accessory_only_solds.transaction_id,accessory_only_solds.quantity,accessory_only_solds.accessory_price,transactions.date_purchased,CAST(accessory_only_solds.accessory_price AS NUMERIC)*accessory_only_solds.quantity AS atotal FROM accessory_only_solds
left join accessories on accessory_only_solds.accessory_id = accessories.id
left join transactions on transactions.id = accessory_only_solds.transaction_id
ORDER BY transactions.date_purchased DESC');
I have problem when I want to display data by json file. If I display data in one table it is ok, but when I want to join more than tables no data displayed
<?php
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
$query = "SELECT Product.Product_Name, Product.Price, Product.Image, Gender.Description, Age.Description, Status.Availability from Product join Age on Age.Age_ID join Gender on Gender.Gender_ID join Status on Status.ID";
$result = mysql_query($query);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['Product_Name'] = $row['Product_Name'];
$row_array['Price'] = $row['Price'];
$row_array['Image'] = base64_encode($row["Image"]);
$row_array['Description'] = $row['Description'];
$row_array['Description'] = $row['Description'];
$row_array['Availability'] = $row['Availability'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db)
?>
Your last join on Status.ID is the issue. Status table doesn't have ID column. Based on you diagram, you have Status.Status_ID (you don't have Status.ID) Also, your data have to have related data where each table has values in common, otherwise, you will get empty results
Your Diagram:
Change your Query
SELECT
Product.Product_Name,
Product.Price,
Product.Image,
Gender.Description,
Age.Description,
Status.Availability
FROM
Product
JOIN
Age ON Age.Age_ID
JOIN
Gender ON Gender.Gender_ID
JOIN
Status ON Status.ID
to
SELECT
Product.Product_Name,
Product.Price,
Product.Image,
Gender.Description,
Age.Description,
`Status`.Availability
FROM
Product
JOIN
Age ON Product.Age_ID = Age.Age_ID
JOIN
Gender ON Product.Gender_ID = Gender.Gender_ID
JOIN
`Status` ON Product.Status_ID = `Status`.Status_ID
For each customer, I want to return: id, name, address, city, cap, country and total of orders. Table names are: customers (10 records) and orders (20 records)
I've tried this code, but it doesn't works
<?php
$conn = mysqli_connect('127.0.0.1','...','...','...') or die("Connection failed: " . $conn->connect_error);
$select = mysqli_query($conn,"SELECT customers.id,customers.name,customers.address,customers.city,customers.cap,customers.country COUNT(customerid) as TotalOrders FROM customers LEFT JOIN orders GROUP BY customer.id");
while($row = mysqli_fetch_array($select,MYSQLI_ASSOC))
{
$tb = <<<table
...{$row['totalorders']}...
table;
echo $tb;
}
mysqli_free_result($select);
echo $num_record = mysqli_affected_rows($conn);
$conn->close();
?>
So something like...
<?php
include('../path/to/connection/stateme.nts');
$query =
"
SELECT c.id
, c.name
, c.address
, c.city
, c.cap
, c.country
COUNT(o.customerid) TotalOrders
FROM customers c
LEFT
JOIN orders o
ON o.customerid = c.id
GROUP
BY c.id;
";
$result = mysqli_query($db,$query); ** where $db is something like mysqli_connect("myhost", "myusername", "mypassword");
while($row = mysqli_fetch_assoc($result))
{
$tb = <<<table
...{$row['totalorders']}...
table;
echo $tb;
}
mysqli_free_result($result);
echo $num_record = mysqli_affected_rows($db);
$db->close();
?>
(I'm no php coder)
You have a comma missing -
customers.country COUNT(customerid)
-----------------^
and you have left out an ON condition -
FROM customers LEFT JOIN orders //ON would be here
One thing you should always do is to create and run your queries against your database before you put those queries in your code. And always, always include error checking.
I am using the following tables:
artists
related_artists
The idea is when I enter an artist's page with an artist_id I can use that id to load related artists. The following code works, but how do I put it in a single query? I can't figure it out.
To connect related_artists with artists I created the following code:
$sql = "SELECT related_artist_id FROM related_artists WHERE artist_id = 1";
$res = mysqli_query($db, $sql);
if (!$res) {
echo "Er is een fout opgetreden.";
exit;
} else {
while ($row = mysqli_fetch_array($res)) {
$query = 'SELECT * FROM artists WHERE artist_id = '.$row["related_artist_id"];
print_r($query."<br />\n");
$result = mysqli_query($db, $query);
if ($result) {
while ($test = mysqli_fetch_array($result)) {
echo $test["lastName"]."<br />\n";
}
} else {
echo "It doesn't work";
exit;
}
}
}
You can just try :
select *
from artists
where artist_id in (
select related_artist_id
from related_artists
WHERE artist_id = 1
);
You can use a LEFT JOIN, try this:
SELECT b.*
FROM related_artist a
LEFT JOIN artists b
USING(artist_id)
WHERE a.artist_id = 1
Should return * from artists, where I aliased artists as b and related_artist as a.
Didn't test, does it work for you / return the expected result?
SELECT * FROM artists where artists.arist_id = 1
INNER JOIN related_artist ON related_artist.artist_id = artists.artist_id
This provides a join on the artist_id columns of both tables, having artist_id = 1. I'm not sure if you need an Inner or a Left join