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
Related
Here is my simple query:
$sql = "SELECT * FROM donations Order By userid";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
I use it to display all data from the 'donations' in a table. Fields are: userid,date,amount.
In that same table, I'd like to add firstname and lastname of corresponding userid which are stored in mymembers table. The condition should be WHERE donations.userid = mymembers.id.
I need help adding that condition for every row resulting from the $sql query.
Use join and change query to
SELECT * FROM donations
INNER JOIN mymembers on (donations.userid = mymembers.id)
Order By donations.userid
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
Ok, so this may sound a little strange and maybe over complicated. Here is the situation. I 2 sets of 3 queries. I will try to make a simple example to explain exactly what I am trying to do:
Queries:
//First set of queries
$query1 = "SELECT Name, Date FROM Table1";
$query2 = "SELECT Type, Place, Location FROM Table2";
$query3 = "SELECT One FROM Table3";
//Second set of queries
$query4 = "SELECT Name, Date FROM Table1 WHERE ID=1";
$query5 = "SELECT Type, Place, Location FROM Table2 WHERE ID=1";
$query6 = "SELECT One FROM Table3 WHERE ID=1";
You just have to trust me when I tell you that I CANNOT combine these two sets of queries. these are over simplified select statements to get the concept of what I am trying to do.
So here is my php code:
//Set 1
$data1 = mysql_query($query1) or die(mysql_error());
$data2 = mysql_query($query2) or die(mysql_error());
$data3 = mysql_query($query3) or die(mysql_error());
while ($line1 = mysql_fetch_array($data1, MYSQL_ASSOC) &&
$line2 = mysql_fetch_array($data2, MYSQL_ASSOC)) {
while ($line3 = mysql_fetch_array($data3, MYSQL_ASSOC)) {
//COMBINE $line1, line2, line3 into a single $lineSet1 -- HOW DO I DO THIS?
}
}
//Set 2
$data4 = mysql_query($query4) or die(mysql_error());
$data5 = mysql_query($query5) or die(mysql_error());
$data6 = mysql_query($query6) or die(mysql_error());
while ($line4 = mysql_fetch_array($data4, MYSQL_ASSOC) &&
$line5 = mysql_fetch_array($data5, MYSQL_ASSOC)) {
while ($line6 = mysql_fetch_array($data6, MYSQL_ASSOC)) {
//COMBINE $line4, line5, line6 into a single $lineSet2 -- HOW DO I DO THIS?
}
}
//Append $lineset1 and $lineset2 so I have 1 resultset $results
$result = array_merge($lineSet1, $lineSet2);
//So now I can pass this $result array into my array2csv function that takes a multidimensional array:
function array2csv(array &$array)
{
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("exportedLeads{$_SESSION['id']}.csv", 'w');
fputcsv($df, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
return ob_get_clean();
}
I know this seems really complicated, but I am pretty confused and not that good at php. Any help would be appreciated. Thanks!
TABLE1:
ID | Name | Date
TABLE2:
ID | Table1_ID | Type | Place | Location
TABLE3:
ID | Table1_ID | One
EDIT: I have been reading into JOIN statements. Is this possible a case for that?
You can resume both of your sets into a single query like using JOIN assuming your ID's match.
First set into 1 query:
SELECT t1.Name, t1.Date, t2.Type, t2.Place, t3.One FROM Table1 t1
JOIN Table2 t2
ON t2.Table1_ID = t1.ID
JOIN Table3 t3
ON t3.Table1_ID = t1.ID
Second set into 1 query:
SELECT t1.Name, t1.Date, t2.Type, t2.Place, T2.Location, t3.One
FROM Table1 t1
JOIN Table2 t2
ON t2.Table1_ID = t1.ID
JOIN Table3 t3
ON t3.Table1_ID = t1.ID
WHERE t1.ID = 1
Assuming your three queries all return the SAME number of rows, you can abuse the assignment operator:
while(($row1 = mysql_fetch($result1))
&& ($row2 = mysql_fetch($result2))
&& ($row3 = mysql_fetch($result3))) {
to fetch from all three result sets in parallel. The downside is that if your result sets are different lengths, you'll only fetch as many records as there are in the SHORTEST result set. e.g. as soon as any of those fetch calls returns false, the entire while aborts, even if there's still data in the other two results.
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";
The code I have below joins 5 tables and then is suppose to sort by date_timed_added. The query worked perfectly if i only join 4 tables. For some reason after the 4th table, its giving me issues. The issue is that it sorts and displays the 5th table first and then the rest follow. How can i fix it so that it sorts date_time_added properly by querying all the other tables?
//$sid is a variable that is drawn from DB
$sql = "select `client_visit`.`visit_id`, `client_visit`.
`why_visit`, `client_visit`.`date_time_added`, `client_visit`.
`just_date`, `client_visit`.`type` from `client_visit` where
`client_visit`.`system_id` = '$sid' and `client_visit`.
`added_by` = '$sid'
UNION
select `client_notes`.`note_id`, `client_notes`.`note_name`,
`client_notes`.`date_time_added`, `client_notes`.`just_date`
, `client_notes`.`type` from `client_notes` where `client_notes`.
`added_by` = '$sid'
UNION
select `client_conditions`.`med_id`, `client_conditions`.`med_name`,
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,
`client_conditions`.`type` from `client_conditions` where
`client_conditions`.`system_id` = '$sid' and `client_conditions`.
`added_by` = '$sid'
UNION
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`,
`client_stats`.`date_time_added`, `client_stats`.`just_date`,
`client_stats`.`type`
from `client_stats` where `client_stats`.`system_id` = '$sid'
and `client_stats`.`added_by` = '$sid'
UNION
select `client_documents`.`doc_id`, `client_documents`.`doc_name`,
`client_documents`.`date_time_added`, `client_documents`.`just_date`,
`client_documents`.`type` from `client_documents` where `client_documents`.
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid'
ORDER BY `date_time_added` DESC LIMIT $startrow, 20";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
//Just using these two variables i can display the same row info
//for all the other tables
$stuffid = htmlspecialchars($row['visit_id']);
$title = htmlspecialchars($row['why_visit');
}
}
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/union.html
If you want to order the ENTIRE result set, the ORDER BY clause must be placed on the LAST query in the UNION, with each query being bracketed.
(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...
sth like this should do.
SELECT Tbl1.field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) Tbl1
ORDER BY Tbl1.field1