Getting id from previous query - php

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

Related

get values from database and work on them

<?php
include('connection.php');
/* code for id goes here */
$q2= "select MAX(id) from usertable";
echo mysqli_query($sql,$q2);
$name=$_POST['name'];
$username=$_POST['usrname'];
$password=$_POST['psw'];
$dob=$_POST['date'];
$query="insert into usertable(name, username, password, dateofbirth) values('$name', '$username','$password','$dob')";
if(mysqli_query($sql,$query))
{
echo "Registered successfully";
}
?>
This is my insert command to register a user in my database. However the database contains a column named id which is the primary key. How do I fetch the id before executing the insert query so that it fetches the last id and increments it by 1 and inserts it in the db along with the other data. The id is numeric and I want the program to perform the operation itself rather than the user entering the data of the id. Please help.
You need to set your id field to auto incement and your database will do it automatically:
ALTER TABLE usertable MODIFY COLUMN id INT auto_increment;
You need to write a query
SELECT MAX(id) FROM usertable
and get the result from that and then increment that value by 1 and then set that value in id field.

How do i insert data a field A - to -B in mysql using PHP?

I have two tables a user table and product
the user is for registering users and login and the product is for allowing the user to post his product. just for listing.
The user table would be like this
user_id (int)
user name (varchar)
user_email (varchar)
user_password)
now i can insert data into and from this table with easily.
In the second table (product table)
product_id (int)
product_name (varchar)
product_description(varchar)
etc.
i have extra field that says user_id
what i basiclly i want to do is, i want insert the user_id from table 1 into a field in table table.
so lets say
i have a form for entering product details
the form include
product_id, name, desc etc all as a textfields
when the user fill all field in that forms, considering that the user is already login, so i want know who inserted that data.
i hope that make sense
The code i used for inserting data into product table is
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$name = $_POST['name'];
$price = $_POST['price'];
$description= $_POST['description'];
$userphone = $_POST['userphone'];
//Creating an sql query
$sql = "INSERT INTO list (name,price,description userphone) VALUES ('$name','$price','$description','$userphone')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Employee Added Successfully';
}else{
echo 'Could Not Add Employee';
}
//Closing the database
mysqli_close($con);
}
So to emphasis
i want the user_id from table 1 to be inserted into table 2.
thanks

Inserting data into multiple tables not functioning correctly

I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement

Save data from a php page into 2 sql table

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());

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