Save data from a php page into 2 sql table - php

Good day!I really need your help guys. Can someone teach me what statements I need to save data into 2 tables. I have 2 tables namely sales and sales_item. The relationship bet. them is the srfno where in sales table it is the PK, so in sales_item table it is the FK. My php form has srfno, date, clientid, clientname, address, contactperson, contactno, returnreason, explanation, refno; these data should be saved in sales table which I already did and it's working brilliantly. My problem now is that qty, serial, desc also include in the form but these should be saved in sales_item table. When I execute the page, it saves the data in sales table and the qty, serial and desc can't save to sales_item table and it didn't get the srfno from sales table.
here's my code for saving qty, serial and desc to sales_item table which is being ignored by my sql statement when saving.
$retitem= "Select `srfno` from sales_item";
$psql= mysql_query($retitem,$con);
$reti = mysql_num_rows($psql);
$reti = $reti + 1;
while($return = mysql_fetch_assoc($psql))
{
if(isset($return['srfno']))
{
$srfno=$return['srfno'];
}
}
$addretex="Insert into `sales_item` (`sitemid`,`srfno`, `retqty`, `retdesc`,`retserial`, `exqty`, `exdesc`,`exserial`,)
VALUES (' ','$srfno', '$qty', '$desc', '$serialno', ' ', ' ', ' ')";
$ret=mysql_query($addretex);

easily you can use LAST_INSERT_ID to insert your last 3 values into table sales_item with related sales id.
INSERT INTO sales (srfno,date,clientid,clientname,address,contactperson,contactno, returnreason,explanation,refno)
VALUES('value1', 'value2','','',...);
INSERT INTO sales_item (sales_id,qty,serial,desc) //sales_id is foreign key came from sales table and its value will be insert automatically by using LAST_INSERT_ID.
VALUES(LAST_INSERT_ID(),'value_1', 'value_2','value_3');

Before Inserting into 'sales_item', you need to check whether $srfno has valid value using
echo "srfno=".$srfno;exit;
if not, you can easily get value of $srfno after inserting into sales table, just do following after inserting into sales table
$srfno=mysql_insert_id();
You can also check error of insert query of sales_item by mysql_error function
mysql_query($addretex) or die("$addretex ".mysql_error());

Related

Getting id from previous query

I have 3 tables that are connected. The insurance table is connected with the customer table and rental details which are also connected with the customer table. I want to insert data into these tables at the same time. What should I put in ID's columns (not the main ID but correlated)? All main ID's are set on auto-increment. I tried with ##IDENTITY and mysql_insert_id.
Here is my code
//inserting into insurance table
if($connection->query("INSERT INTO insurance (Collision_Coverage,
Medical_Coverage) VALUES ('$collision_coverage','$medical_coverage')"))
{
//inserting into customer table
if($connection->query("INSERT INTO customer (People_ID, Driving_License_No, Insurance_id) VALUES ('$current_user_id', '$driv_lic_num', ##IDENTITY)"))
{
//inserting into rental_details table
if($connection->query("INSERT INTO rental_details (Vehicle_ID,Customer_ID, Hire_Date, Hire_Days, Total_cost, Return_date) VALUES ('$current_vehicle_id', ##IDENTITY, '$pick_up_date', '$days_hired', '$total_cost', '$returning_date')"))
use insert_id to get the last insert id
$lastId = $connection->insert_id;
echo $lastId;
here is the reference

How to use Insert query with multiple tables at a same time?

I have one form let's say bill form. i have 3 tables.
bill (billId->primary key)
billdetails (billdetailId->primary key, billId-> foregin key)
fintran (finalId -> primary key, there are total 10 inputs in form.
On submit first 5 input should go in bill table and other 5 input should go in bill details. And all will go in final table. i used below query for this.
BEGIN;
$sql = mysqli_query($conn,"INSERT INTO `bill`(`societyId`, `unitId`, `memberId`, `area`, `arrear`, `invoiceNumber`, `invoiceDate`, `dueDate`, `billingPeriod`, `total`, `interestOnArrear`, `totalDue`, `email`, `penalty`, `principalArrears`, `interestArrears`, `advancedAdjusted`, `netPending`) VALUES ('".$societyId."','".$unitId."','".$memberId."','".$area."','".$arrear."','".$invoiceNumber."','".$invoiceDate."','".$dueDate."','".$billingPeriod."','".$total."','".$interestOnArrear."','".$totalDue."','".$email."','".$penalty."','".$principalArrears."','".$interestArrears."','".$advancedAdjusted."','".$netPending."')");
$memo = $_REQUEST['memo'];
$charge = $_REQUEST['charge'];
$sql= mysqli_query($conn,"INSERT INTO `billdetail`(`biilId`, `memo`, `charge`) VALUES (LAST_INSERT_ID(),'".$memo."','".$charge."')");
$sql= mysqli_query($conn,"INSERT INTO `fintran`(`societyId`, `docId`, `docTypeName`, `docDate`, `unitId`, `unitName`, `memberId`, `memberName`, `comboId`, `ledgerId`, `ledgerName`, `debit`, `credit`, `netValue`) VALUES ('".$societyId."',LAST_INSERT_ID(),'bill','','".$unitId."','".$unitId."','".$memberId."','".$memberId."','','".$charge."','','','','')");
COMMIT;
after insert data i want billId i.e primary key of bill table in both billdetails and fintran table. but with this query i'm able to get this in only billdetail table. In fintran table i get primary key of billdetail table. please help me with the same.
No, you can't insert into multiple tables in one MySQL command. You can however use transactions.
Check this : MySQL Insert into multiple tables? (Database normalization?)

How can I insert data to a table which has a foreign key, from a table which has a primary key auto-increment?

I have 4 mySQL tables with the following entries:
user
-user_id PK,AI
-user_name
-user_mobil
-user_passw
-user_email
bookingdetails
-booking_id PK,AI
-booking_date
-booking_time
-person_number
booking
-booking-_id FK
-restaurant_id CK
-user_id CK
restaurant
-restaurant_id PK
-restaurant_name
-restaurant_address
-restaurant_description
I would like to make a booking, I insert all the bookingdetails data, which gives me a AI booking_id, and after I would like to make my booking table and insert the restaurant_id and the user_id With the same booking_id which was given by the bookingdetails table.
I made the following code for achieve that in php on a localserver:
$booking_date=$_POST["booking_date"];
$booking_time=$_POST["booking_time"];
$number_of_place=$_POST["number_of_place"];
$customer_id=$_POST["customer_id"];
$restaurant_id=$_POST["restaurant_id"];
$res;
$sql_query = "INSERT INTO bookingdetails(booking_date, booking_time, number_of_place) VALUES ('$booking_date','$booking_time', '$number_of_place')";
$sql_query2 = "INSERT INTO `booking`(`booking_id`, `customer_id`, `restaurant_id`) SELECT booking_id, '$customer_id', '$restaurant_id' FROM bookingdetails ORDER BY booking_id DESC LIMIT 1 ;";
if(mysqli_query($con,$sql_query))
{
}
else
{
}
if(mysqli_query($con,$sql_query2))
{
}
else
{
}
?>
Is that a legit solution on a server which joining to an Android app? Is there any case, that i don't get the good id on the second query? What would be a better solution?
Answer given in comment by #Mark Ng
Use last insert id, criteria is that your pk has to be AI.
The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) used in the last query.
Source: w3schools.com/php/php_mysql_insert_lastid.asp
To elaborate
you have to execute the query from which you need the last inserted id, then you can access that by using
$last_id = $conn->insert_id;
which in turn you can use for your following query.
Note:
I see you use a query to use the results for your insert query, but your syntax is incorrect (your missing values)

Not inserting values to database when data is similar

I am working on a payroll system. The admin is able to successfully save these data but when an employee ID, which is already in the database, is selected, it is not added to the database. Here is my code:
$sql = "INSERT INTO payroll VALUES('$id','$period','$paidDays','$hourlyRate','$hoursworked','$overtime','$overtimePay','$undertime','undertimePay','$sss','$philHealth','$pagibig','$OtherDeductions','$tax','$grossPay','$netPay')";
I need to solve this to be able to do the Salary History of the employees.
PLEASE NOTE that this code is working. It's just that when a similar employee is inputted, it is not added to the database. Thanks!
EDITED: THIS is the table structure
Look at your table structure, Id must be PRIMARY KEY that is why it can't be added when you select an existing id.
As primary key can not be duplicated, so if you want to have that process, the structure have to be changed.
I assume that '....similiar employee...' is defined by ID, and this might give you a hints :
Insert Into Payroll
Select id,period,paidDays,hourlyRate,hoursworked, overtime,overtimePay,
undertime,undertimePay,sss,philHealth,pagibig,OtherDeductions,
tax,grossPay,netPay
FROM (
select '$id' AS ID,'$period' AS period,'$paidDays' AS paidDays,
'$hourlyRate' AS hourlyRate, '$hoursworked' AS hoursworked,
'$overtime' AS overtime,'$overtimePay' AS overtimePay,
'$undertime' AS undertime,'undertimePay' AS undertimePay,
'$sss' AS sss,'$philHealth' AS philHealth,'$pagibig' AS pagibig,
'$OtherDeductions' AS OtherDeductions,'$tax' AS tax,
'$grossPay' AS grossPay,'$netPay' AS netPay, 0 AS JUM
UNION ALL
select id,period,paidDays,hourlyRate,hoursworked, overtime,
overtimePay, undertime,undertimePay,sss,philHealth,pagibig,
OtherDeductions,tax,grossPay,netPay, 1 AS JUM
from [YourTable]
Where [ID] = [EmployeeID]) AS T
GROUP BY id,period,paidDays,hourlyRate,hoursworked, overtime,
overtimePay, undertime,undertimePay,sss,philHealth,pagibig,
OtherDeductions,tax,grossPay,netPay
HAVING SUM(JUM) <0

PHP MYSQL database structure, multiple queries for one entry

I'm building a fairly simple site to keep track of of some sales for work. It involves a mysql database with multiple tables for each entry. For the most part, the relationships are cut and dry. However, I have a comments table that will store multiple comments for the same sale. I have a foreign key in the comments table tied to the ID of the main sales table. I have a similar arrangement between a gross table and the sales table, in that it stores multiple gross amounts for the same saleID. What is the best way to insert these into the database? Currently, I'm inserting the comments and getting the ID of that row, then inserting the gross and getting the ID, then I make the insertion into the sales table using the comments id and the gross id. Is there a more efficient method rather than making 5 queries?
--Edit: Here is the current code. I'm pretty new to this so I had to look up procedures to see what you meant. It seems like it's basically what I'm doing, but creating a method for it instead, which I'll be doing once I figure out the most efficient way.
//Prepare the Queries
//Insert Gross Amounts Query
$grossQ = "INSERT INTO gross (commGross, storeGross, manGross, fiGross, flatGross) VALUES ('$commGross', '$storeGross', '$manGross', '$fiGross')";
//Insert Comments Query
$commentsQ = "INSERT INTO comments (comment, dealcomment, grosscomment) VALUES ('$otherComments', '$dealComments', $grossComments')";
//Insert Deal Query
$q = "INSERT INTO sales (make, model, location, vehtype, saletype, manager, county, flat, unitcount, armoramount, controlnumber, salesman, stock) VALUES ('$make', '$model', '$location', '$vehType', '$saleType', '$managerName', '$county', '$flat', '$unitCount', '$armorAmount', '$controlNumber', '$salesmanName1', '$stock')";
//Make database connection
$db = new db('palm_sales');
//Execute gross query and get the id of the row
$db->execute($grossQ);
$grossID = $db->getLastID();
//Execute comments query and get the id of the row
$db->execute($commentsQ);
$commentsID = $db->getLastID();
//Build Main Query
$q = "INSERT INTO sales (make, model, location, vehtype, saletype, manager, gross, comments, county, flat, unitcount, armoramount, controlnumber, salesman, stock) VALUES ('$make', '$model', '$location', '$vehType', '$saleType', '$managerName', '$grossID', '$commentsID', '$county', '$flat', '$unitCount', '$armorAmount', '$controlNumber', '$salesmanName1', '$stock')";
//Execute Main Query
$db->execute($q);
if(mysql_affected_rows() > 0)
{
echo "Success!";
}
else echo "Error: ".mysql_error();
It sounds like you're only performing 3 queries at the moment - mysql_insert_id() does not perform a new query, it gives your information about the insert just performed.
It's not clear why you need to insert into the sales table when you insert a comment or gross. I would imagine you'd have something like this:
TABLE sales PK id
TABLE comments PK id FK sales_id
TABLE gross PK id FK sales_id
When you get a new sale, you insert into the sales table. To add a new comment or gross, you insert into that table, with a foreign key of the sales ID. What part of that is not working?

Categories