I have a SELECT staement where I JOIN 2 separate tables.
$result = mysql_query('SELECT * FROM (SELECT * FROM gslil0009) as table1 UNION SELECT * FROM (SELECT * FROM gslil0028) as table2' . ' ORDER BY lname');
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
}
How do I print out which table the row came from?
$result = mysql_query('SELECT *,'tbl1' FROM (SELECT * FROM gslil0009) as table1
UNION SELECT *,'tbl2' FROM (SELECT * FROM gslil0028) as table2'
. ' ORDER BY lname');
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
echo $row['tbl1'];
}
I used the same solution as sel just add backslash to avoid error and added a name to the table names.
$result = mysql_query('SELECT *,\'table1\' AS tablename FROM (SELECT * FROM gslil0009) as table1
UNION SELECT *,\'table2\' AS tablename FROM (SELECT * FROM gslil0028) as table2'
. ' ORDER BY lname');
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
echo $row['tablename'];
}
i couldn't add comment on his post.
Related
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}";
Sudipta's suggestion worked. Now I am having difficulty getting the final script to display online. The script displays properly in phpMyAdmin SQL editor.
$sql = "CREATE TABLE Inv_Physical_Count
SELECT SUM(qty) as qty, excel_part_num, part_id, part_desc, order_form_seq
FROM Inventory, Inventory_Items, Parts
WHERE Inventory.id = Inventory_Items.inventory_id
AND Inventory_Items.part_id = Parts.id
AND Inventory.date = '2017-01-05'
AND Inventory.inv_type_id = '2'
GROUP BY part_id
ORDER BY part_id";
$q = $pdo->prepare($sql);
$q->execute(array());
$sql = "CREATE TABLE Inv_Restock
SELECT SUM(qty) as qty, excel_part_num, part_id, part_desc, order_form_seq
FROM Inventory, Inventory_Items, Parts
WHERE Inventory.id = Inventory_Items.inventory_id
AND Inventory_Items.part_id = Parts.id
AND Inventory.date >= '2017-01-05'
AND Inventory.date < '2017-07-04'
AND Inventory.inv_type_id = '1'
GROUP BY part_id
ORDER BY part_id";
$q = $pdo->prepare($sql);
$q->execute(array());
$sql = "CREATE TABLE Inv_Orders
SELECT SUM(qty) as qty, excel_part_num, part_id, part_desc, order_form_seq
FROM Orders, Order_Items, Parts
WHERE Orders.id = Order_Items.orders_id
AND Order_Items.part_id = Parts.id
AND Orders.date_order >= '2017-01-05'
AND Orders.date_order < '2017-07-04'
GROUP BY part_id
ORDER BY part_id";
$q = $pdo->prepare($sql);
$q->execute(array());
The following SQL script works in SQL Editor in phpMyAdmin. However, in PHP I cannot get this script to display real content. It is all blank.
$sql = "SELECT a.qty + b.qty - c.qty as 'QTY', a.excel_part_num as 'Part Num', a.part_desc as 'Description'
FROM Inv_Physical_Count a,
Inv_Restock b,
Inv_Orders c
WHERE a.part_id = b.part_id
AND a.part_id = c.part_id
ORDER BY a.order_form_seq";
$q = $pdo->prepare($sql);
$q->execute(array());
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>' . $row['qty'] . '</td>';
echo '<td>' . $row['excel_part_num'] . '</td>';
echo '<td>' . $row['part_desc'] . '</td>';
}
Can you not combine all your queries as per below. It will work, if you have the same part_id, if its not same, maybe you can join the tables with part_num and not part_id
SELECT SUM(a.qty + b.qty - c.qty), part_num
FROM Phys_Count a
LEFT JOIN Items_Received b
ON a.part_id = b.part_id
JOIN items_shipped c
ON a.part_id = c.part_id
WHERE ...
GROUP BY part_num
ORDER BY part_id
I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}
I'm trying to get the averages from the rating column of my table, then display a row in a HTML table for each distinct div_id and its average rating, in descending order. I know this should probably be easy, but I'm having a hard time figuring it out. Any help would be greatly appreciated.
<?php
mysql_connect($db_server, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_database) or die(mysql_error());
$result = mysql_query("SELECT * FROM ratings") or die(mysql_error());
while($row = mysql_fetch_object( $result )){
$ad = $row->div_id;
$result2 = mysql_query("SELECT div_id, avg(rating) AS avg, COUNT(*) FROM ratings WHERE div_id = '" . $ad . "' ORDER BY div_id DESC ") or die(mysql_error());
while($row2 = mysql_fetch_array( $result2 )){
$adid = $row2[0];
$count = $row2[2];
$avg = round($row2[1],2);
echo "<tr><td>";
echo $adid;
echo "</td><td>";
echo $avg;
echo "</td></tr>";
}
}
?>
Instead do tow queries, you can use the GROUP BY term in only one query.
SELECT div_id, avg(rating) AS avg, COUNT(*) FROM ratings GROUP BY div_id ORDER BY div_id DESC
php code
<?php
mysql_connect($db_server, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_database) or die(mysql_error());
$result = mysql_query("SELECT div_id, avg(rating) AS avg, COUNT(*) FROM ratings GROUP BY div_id ORDER BY avg DESC") or die(mysql_error());
while($row = mysql_fetch_array( $result )){
$adid = $row[0];
$count = $row[2];
$avg = round($row[1],2);
echo "<tr><td>" . $adid . "</td><td>" . $avg . "</td></tr>";
}
?>
Perhaps you should try doing this all in one query:
SELECT div_id, avg(rating) AS avgrating, COUNT(*) as cnt
FROM ratings
GROUP BY div_id
ORDER BY avgrating desc;
I need to use an echo $_GET['id']; in oci_parse but cannot seem to get it working. I have tried escaping it in ', " etc. but neither have worked.
Code:
$stid = oci_parse($conn, "
SELECT COLA,
(SELECT COLB FROM T2 WHERE T2.COLB = echo $_GET['id'];)
FROM T1
WHERE T1.COLA = echo $_GET['id'];
");
Method 1
$stid = oci_parse($conn, "SELECT COLA,
(SELECT COLB FROM T2 WHERE T2.COLB = {$_GET['id']})
FROM T1
WHERE T1.COLA = {$_GET['id']}");
Method - 2
$stid = oci_parse($conn, "SELECT COLA,
(SELECT COLB FROM T2 WHERE T2.COLB = ".$_GET['id'].")
FROM T1
WHERE T1.COLA = ".$_GET['id']."");
you have to do some validation before using it inside the query ..
if (ctype_digit($_GET['id'])){
$dIdUser = $_GET['id'];
$stid = oci_parse($conn, "
SELECT COLA,
(SELECT COLB FROM T2 WHERE T2.COLB =$dIdUser ;)
FROM T1
WHERE T1.COLA = $dIdUser;
");
}
Maybe you need after query first execute the query?
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>