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.
Related
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
An explaination of how my code works:
I have a pure select on a database that is filled through a different program. I am selecting data to check up on orders. Now I want to give a ready status to the order, which cannot be inserted into the database I am selecting from, so I created a small different database to insert the ordernumber (from the previous selection) into that database and insert a 1. This can be updated to a 0 by pressing the button again.
Now I want to show my orders as the following:
An order can have the status, but doesn't have to have a status.
If it doesnt have a status it should show in the list.
With my current code (below) it only shows orders that are present in the 2nd optional database, I understand why this is happening. But I can't manage to work out a solution to show everything even if an ordernumber is not present in the 2nd optional database.
while( $row = sqlsrv_fetch_array( $stmt1, SQLSRV_FETCH_ASSOC) ) {
$statusorder = $row['ordernr']; //Ordernumber selected in primary database
$sqlstatus = "SELECT status from status WHERE Ordernr = '$statusorder'"; //selecting the status from optional database
$result = $conn2->query($sqlstatus);
while($row2 = $result->fetch_assoc()) {
<insertmyhtmlhere>
}
}
You can use only one query to get all data. Just use database.Table.column
This will display all order id of table database1.ordersTable
SELECT db1.id FROM database1.`ordersTable` db1
This will display all status of table database2.statusTable
SELECT db2.status FROM database2.`statusTable` db2
Now just combine with LEFT JOIN to show all rows whether it exists or not.
SELECT db1.id, db2.`status`
FROM database1.`ordersTable` db1
LEFT JOIN database2.`statusTable` db2
ON db1.`id` = db2.`status`;
DonĀ“t forget to use Condition to filter, in this case, the same order id.
ON db1.`id` = db2.`status`;
If databases haves different COLLATION you can use this:
SELECT db1.`id', db2.`status`
FROM database1.`ordersTable` COLLATE utf8mb4_spanish_ci db1
LEFT JOIN database2.`statusTable` COLLATE utf8mb4_spanish_ci db2
ON db1.`id` = db2.`status`;
Here are a sample fiddle
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
How would I go about deleting a row from the table 'subjects' that has a primary id 'subject_id' based on the number of rows in another table named 'replies' that uses a 'subject_id' column as a reference.
Example in pseudo code:
If ('subject' has less than 1 reply){
delete 'subject'}
I don't know much about SQL triggers so I have no clue if I would be able to incorporate this directly in the database or if I'd have to write some PHP code to handle this...
To delete any subjects that have had no replies, this query should do the trick:
DELETE s.* FROM subjects AS s
WHERE NOT EXISTS
(
SELECT r.subject_id
FROM replies AS r
WHERE r.subject_id = s.subject_id
);
Demo: DB Fiddle Example
One of the MySQL gurus will need to weigh in on whether or not you can do this directly, but in PHP you could...
$query = "SELECT subject_id FROM subjects WHERE subject='test'";
$return = mysqli_query($mysqli, $query);
$id = mysqli_fetch_assoc($return);
$query = "SELECT reply_id FROM replies WHERE subject_id='".$id[0]."'";
$return = mysqli_query($mysqli, $query);
if(mysqli_num_rows($return) < 1){
$query = "DELETE FROM subjects WHERE subject_id='1'";
$return = mysqli_query($mysqli, $query);
}
This example assumes the "subject" is unique. In other words, SELECTing WHERE subject='test' will only ever return one subject_id. If you were doing this as a periodic cleaning, you would grab all the subject_id values (no WHERE clause) and loop through them to remove them if no replies.
You can achieve this in one query by selecting all (unique) subject-ids from the replies table, and delete all subjects that doesn't have a reply in there. Using SELECT DISTINCT, you don't get the IDs more than once (if a subject has more than one reply), so you don't get unnecessary data.
DELETE FROM subjects
WHERE subject_id NOT IN (SELECT DISTINCT subject_id FROM replies)
Any subject that doesn't have a reply should be deleted!
So you want to delete all subjects with no replies:
DELETE FROM subjects WHERE subject_id NOT IN
(SELECT subject_id FROM replies);
I think this is what you want...
i want to display record related to a specific primary key based on the foreign keys in other tables. How to display records for that primary key in other tables using php??
for example:
table1
primary key 1: plate#1
primary key 2: plate#2
primary key 3: plate#3
table2
primary key 1: destination|route|revenue|plate# 1
primary key 2: destination|route|revenue|plate# 3
table3
primary key 1: diesel price|number of liters|plate# 1
primary key 2: diesel price|number of liters|plate# 3
I already created a page that will display all the data in table1. I want to display the data in table1 and table2 that are related to the data in table1 when I made the database they already had relationship with each other. My problem is just displaying the record related to table1. I want to display records for just plate#1, another for plate#2 and so on.
Here's a crude example:
<?php
$truck_id = mysql_real_escape_string($_GET['truck_id']);
$sql_PK = "SELECT * FROM table1 WHERE id = '{$truck_id}'";
$res_PK = mysql_query($sql_PK);
$row_PK = mysql_fetch_assoc($res_PK);
$truck_plate = $row_PK['plate'];
$truck_plate = mysql_real_escape_string($truck_plate);
$sql = "SELECT table2.plate, table2.destination, table2.route, table3.plate, table3.diesel_price, table3.num_of_liters FROM table2, table3 WHERE table2.plate = table3.plate AND table2.plate = '{$truck_plate}'";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($res);
// this will give you the details from the following
//TABLE2
// plate
// destination
// route
//TABLE3
// plate
// diesel_price
// num_of_liters
?>
There's a couple of important things to remember. First is get in the habit of naming your fields without spaces in the database and use _ instead. so diesel price is diesel_price, etc. Secondly is to make sure that you are protecting yourself from any injections like I have shown here using the mysql_real_escape_string
So when someone clicks on truckdetails.php?plate=mrtchi it's going to query the database based on the plate number: mrtchi
You are probably looking to join tables to get the final results. Join allows you to essentially merge tables together and get a single result based on the selections. Google php mysql join table and look at some of the examples. Here's one for you: Join Tables