How to show data with combining of 2 tables? - php

I have a table named purchase_details_master and another is sales_detais_master Where all the purchase and sales details are available.
Structure of Purchase Table: These are the data which I have purchased
Structure of Sales Table: These are the data which I have sell
Now I need to show the data like this, This image is showing the iPhone 12 data. In the Inward field showing tha pieces of purchased item, In the Outward field showing the data of sells pieces, and the closing data showing like Opening + Inward or Opening - Outward = Closing
I am using Core Php with Sqlite database
$item = $_POST['item'];
$sql = "SELECT * FROM purchase_details_master WHERE item_id = '$item'";
$sql_run = $conn->query($sql);
I have used while loop it's not solving the problem
Kindly solve this out for me! Thank you in Advance

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
like that.
SELECT * FROM purchase_details_master AS pdm INNER JOIN sales_detais_master AS sdm ON sdm.item_id = pdm.item_id WHERE sdm.item_id = ?

this will select all fields from the two tables
$sql = "SELECT * FROM purchase_details_master, sales_detais_master WHERE purchase_details_master.item_id = '$item' AND purchase_details_master.item_id = sales_details_master.item_id";
or select exact fields from the two tables
SELECT table1.field1, table1.field2, table2.field1, table2.field3
FROM table1, table2,
WHERE table1.field1 = something, or table1.field1 = table2.field2

Related

Get value from a table through an ID from another table

So basically I have a table : "task":
- id - morada -
- 1 - 1 -
And a "moradas" table:
- ID - Morada - CodPostal
- 1 - Street 1th - 1523
I want through task.Address from the task table get the Address and Postal Code from the moradas table. Right now I'm only showing the int number of the address in the trip table.
<td><?php echo $fetch['address']?></td>
The query I have now is this
$query = $conn->query("SELECT * FROM `task` WHERE status != 'Done' ORDER BY `id` ASC");
How do I get the values from the Address table with that int and show them in that echo?
You can user INNER JOIN for joining the two tables and get data from them.
INNER JOIN is used in this context assuming that each address id from database Trip corresponds to the actual address from database table: address.
SELECT T.Trip, A.Address, A.Postal_Code FROM Trip T
INNER JOIN address A ON T.Address = A.Address_ID
Note:
Your specified field names contain spaces.
I have added underscores instead of spaces in them.
Please put proper field names here.
Reference:
EDIT:
Updated Query as per updated question:
SELECT T.id, A.Morada, A.CodPostal FROM task T
INNER JOIN moradas A ON T.morada = A.ID
Updated according to your tables and columns.
If you want address and postal code where your task.id and moradas.id value matches, then you should join two tables and get address and postal code from moradas table -
Try this :-
$sql = "SELECT
task.id,
CONCAT(
moradas.`Morada`,
' ',
moradas.`CodPostal`
) AS address
FROM
task
LEFT JOIN moradas
ON (task.id = moradas.id)
WHERE task.`status` != 'Done'
ORDER BY task.id ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Address : " . $row["address"]."<br>";
}
} else {
echo "0 results returned";
}
$conn->close();
I assume that status column is in your task table
This query will show your address and postal code as one column address. If you want those into saperate columns, you can skip concat and select Morada and CodPostal separately.
Follow this scheme always as I will show you regarding your table names
If you have big data in MySQL like name. Postal code Id. And suppose you have addresses in another table witch related to another tracking services as example
$ret = mysql_query("select t2.id, t2.name, t2.phone, t1.address From t2 Left join t1 on t2.id = t1.id where t2.id = $id ")
// $id = is variable you get from php request like $_GET and id table should have index in MySQL then do the following
echo'<table>'
While ($row = mysql_fetch_assoc($ret) {
echo"<td>" .$row["addresse"]."<td>";
// repeat this for all retrieved data
}
echo '</table>'
Now you will have table in php output with all data in the query.
If query returns one record so table will have one result
If query have 10000 records as result so table will have 10000
You may put limit in query to retrieve 100 result per request

Fetching all Data from Multiple tables based on Single id

I have to select data from multiple tables based on single key value. I have one table called maintable where I will get all the ids from, and i have another 10 tables in the same database which have maintable.id as a foreign key. Now I have to retrieve data from the 10 tables where maintable.id matches in one single table.
The code I have tried is:
$sql = select id from maintable;
$runsql = mysql_query($sql);
while($sqlRow = mysql_fetch_array($runsql ,MYSQL_ASSOC)) {
for($i=1;$i<=10(This is another table count);$i++) {
$servSql = "select * from table.$i where ref_id = ".$sqlRow['id'];
$runServerSql = mysql_query($servSql);
while($serverRow = mysql_fetch_array($runServSql,MYSQL_ASSOC)) {
}
}
}
Try something like this in a join:
SELECT * FROM maintable m
INNER JOIN othertable o
ON m.id = o.id
That will select from both tables using an inner join ON the id column. You may want to look up a basic SQL tutorial to learn the basic types of joins you can use. Good luck!

Selecting from two tables issue

This is was am trying to do table A has all profession categories & table B has users details.i want select from the 2 tables and match up categories selected,if user select 'web developer' from a dropdown of categories.i want to display list of users under web developer.
<?php
$q = intval($_GET['q']);
//select state of the two tables here
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
///
<?php }?>
it's unclear from the question and lack of database details what and how to do the sql query ( which I think is what you are actually asking for ) but something along these lines perhaps.
select * from `tableB` b
left outer join `tableA` a on a.`professionid`=b.`professionid`
where a.`profession`='Web Developer'

Mysql query working from command line but only half working in PHP

I have two tables
1.owners
id
firstname
lastname
2.product
id
id2
id3
item
SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='Jezebel';
Works fine from the command line returning all relevant items from owners and product but using the following PHP
$result = mysql_query("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='".$_POST['fname']."'")
only returns results from the table owners.
I have googled extensively and don't see anyone else with this problem.
$fname= $_POST['fname'];
$result = mysql_query("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='$fname'")
First, make your query similar to this
$query = sprintf("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='%s'",mysql_real_escape_string(trim($_POST['fname'])));
$result = mysql_query($query) or die(mysql_error());
var_dump(mysql_fetch_assoc($result));
and let me know the result so I can update this answer.
First of all: You have two table which match on autoincrement column id?
However, try this?
SELECT tb1.id, tb1. firstname, tb1.lastname, tb2.id, tb2.id2, tb2.id3, tb2.item FROM owners AS tb1 LEFT JOIN product AS tb2 ON tb2.id=tb1.id where tb1.firstname=$fname
I have found the error. It was nothing to do with the select statement. I had a typo in the display code. It should have been like this
echo "</td><td>";
echo $row['id3'];
But was like this instead
echo "</td></td>";
echo $row['id3'];
Thank you all for your help.

PHP/ MYSQL Inserting Data Into Multiple Tables

I am trying to add data into 3 table using PHP, atm I can only view the results of the tables that are joined .
RESULTS QUERY
$sql = mysql_query("SELECT PART_ID, PART_DESC, SERIAL_NUM, PART.RACK_NUM, PART.PART_TYPE_ID, PART_TYPE_DESC, LOCATION
FROM PART
INNER JOIN PART_TYPE ON PART.PART_TYPE_ID = PART_TYPE.PART_TYPE_ID
INNER JOIN RACK ON RACK.RACK_NUM = PART.RACK_NUM
This will get all the rows from the PART table, and for each of the rows we find, match that row to a row in the PART_TYPE table (the condition being that they have the same PART_TYPE_ID). If no match between the PART and PART_TYPE tables can be found for a given row in the PART table, that row will not be included in the result.
My Insert Query This is where im having trouble
How do I add the data to the PART_ID, PART_TYPE and RACK tables?
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['PART_ID'])) {
$id = mysql_real_escape_string($_POST['PART_ID']);
$PART_DESC = mysql_real_escape_string($_POST['PART_DESC']);
$SERIAL_NUM = mysql_real_escape_string($_POST['SERIAL_NUM']);
$RACK_NUM = mysql_real_escape_string($_POST['RACK_NUM']);
$PART_TYPE_ID = mysql_real_escape_string($_POST['PART_TYPE_ID']);
$LOCATION = mysql_real_escape_string($_POST['LOCATION']);
$PART_TYPE_DESC = mysql_real_escape_string($_POST['PART_TYPE_DESC']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT PART_ID FROM PART WHERE PART_ID='$id' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
**$sql = mysql_query("INSERT INTO PART (PART_ID, PART_DESC, SERIAL_NUM, RACK_NUM, PART_TYPE_ID)
VALUES('$id','$PART_DESC','$SERIAL_NUM','$RACK_NUM','$PART_TYPE_ID')") or die (mysql_error());**
header("location: inventory_list.php");
exit();
}
?>
Micheal if I understood your problem you just need to do 2 other SQL INSERT to add data in the other table
$sql = mysql_query("INSERT INTO PART (PART_ID, PART_DESC, SERIAL_NUM, RACK_NUM, PART_TYPE_ID)
VALUES('$id','$PART_DESC','$SERIAL_NUM','$RACK_NUM','$PART_TYPE_ID')") or die (mysql_error());
$currentID = mysql_inserted_id();
$sql2 = mysql_query("INSERT INTO PART_TYPE [..]");
$sql3 = mysql_query("INSERT INTO RACK [..]");
You can use $currentID if you need the ID of the last record inersted into PART
But still I strongly suggest you to learn PDO http://php.net/pdo for sql
your table management is wrong, you never use arrows just to show that you are joining it with that table from this table, but rather from the key in first table to foreign key in the second table, that's what i would start from, maybe a better idea would be to join them using JOIN look up in google how joins are working, that may be the cause...
I agree with #yes123, that is the correct way to insert into tables, if you have a program called heidisql then use it, because there is a window to run your queries... that way to test if it is properly written also use mysql_error.
Debug, debug, and one more time debug your code.
Your tables are not correctly designed.
Try this table structures .
In your base table Part. -
The columns in this should be:
Part_id
part_desc
serial_num
The part_type should have following columns:
part_type_id
part_type_desc
part_id -> foreign key to the parent table
The rack table should be:
Rack_num
location
part_id -> foreign key to the parent table.
So your select query to get all the part related information would be:
$sql="select * from part join part_type pt on tp.part_id=part.part_id join Rack_num rn on rn.part_id=part.part_id";
With this structure the data remains normalized. And is flexible, so if the parts are on multiple racks you just go to the rack table and add and new rack number and the part id.

Categories