How to get current rows data after inserting element. - php

I have four fields in table id, name, city & state. I am inserting name , city & state. and id is auto increament
$mysql_register_resultset= mysqli_query($con, "INSERT into vendor (username, city, state) VALUES( '$name','$city','$state')");
It is successfully sumitted. I want that id value on next line of insertion. and i will process with that id.
How to get current id after insertion.

use this
$last_inserted_id = mysqli_insert_id($con) ;

Related

How to insert data to another table by id

I want to complete user sign up.
firstly user will write username and password, table called users, I have id as primary key.
secondly user will write address, phone number and zipcode, table called userdata, I have userid as index(key).
I have did a relation between id from table user and userid from table userdata.
So now I want to insert data from php code I did two forms one for user and it has two input for username and password it works well and data inserted.
in the second form I have select option has id from table users and it works well.
then in the same form I have three inputs phone number, address and zipcode.
so the question is how I can insert the data to userdata by the same to the same id. so userid in table user will be the same id in table userdata.
I need sql code.
I used that :
"INSERT INTO userdata(address, phone, zipcode) VALUE (:address, :phone, :zip) SELECT 'id' FROM 'users';"
First :
$q = "NSERT INTO users(username, password) VALUE ('Adam', '12345678')";
$r = $connect->query($q);
//get the last id u inserted
$last_id = mysqli_insert_id($connect);
Second :
$q = "NSERT INTO userdata(address, phone, zipcode,user_id) VALUE ('California', '12345678', '1111','$last_id')";
$r = $connect->query($q);
and if you want to make the (id) not the (userid) the same just :
$q = "NSERT INTO userdata(id, address, phone, zipcode) VALUE ('$last_id','California', '12345678', '1111')";
$r = $connect->query($q);

How can I copy a data inserted from table to be inserted in another table?

I have two tables
transaction_tbl
order_tbl
I inserted data in transaction_tbl with a primary key autoincrement transaction_no.
Now, I need to insert data in order_tbl with columns
orderitem_no(AI, PK),
transaction_no,
product_sku,
quantity
How can I sync the transaction_no from transaction table in one process?
I just assign data to variables then:
My current code is
$sql0 = "INSERT INTO transaction_tbl (transaction_no, transaction_date, customer_name) VALUE ('', now(), '$customer_name');";
$x=0;
while ($x!=5){
$sql1 = "INSERT INTO order_tbl
(orderitem_no, transaction_no, product_sku, quantity)
VALUE ('', '', '$product_sku', '$quantity');";
$x=$x+1;
}
Nothing next. Sorry, Im super lost.
Im planning to run ths sql's in one process.
transaction_no in transaction_tbl is auto increment.
I have fk_trans_no in order_tbl.
And then I totally lost. orderitem_no is auto increment but what will I do to the transaction_no?

Insert data into table and immediately select ID number of the row

I have a MYSQL table called 'Buyers'. I am taking form data and inserting it into the table on a page called insert.php.
Now, along with the column names for the form fields, I have an Auto-increment ID column in the table. What I want is; once I send the form data to the table, I want to then execute some SQL to get the ID number for the row into which I just inserted the data into.
E.g, I have the SQL:
INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]');
This will create a row in the 'Buyers' table with the data from form fields 'name', 'email' and 'job'.
This row will have an ID number generated by Auto Increment.
How, then, can I then select that exact ID number? Is there some way to select the most recent row in the table, since that is the row which contains the ID number I want?
Mysqli : mysqli_insert_id()
<?php
mysqli_query($con,"INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysqli_insert_id($con);
?>
PDO : PDO::lastInsertId()
<?php
$stmt = $con->prepare("INSERT INTO Buyers (name, email, job) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['email'], $_POST['job']);
$stmt->execute();
$last_id = $con->lastInsertId();
?>
Assuming $con as connection.
Mysql : mysql_insert_id()
<?php
mysql_query("INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysql_insert_id();
?>
NOTE: [The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead ]
SELECT x.*
FROM messages x
JOIN
( SELECT from_id, MAX(time_sent) time_sent GROUP BY from_id ) y
ON y.from_id = x.from_id
AND y.time_sent = x.time_sent;
The last part of this puzzle is left as an exercise for the reader.
Use mysql_insert_id() to retrive ID. More details - http://php.net/manual/en/function.mysql-insert-id.php

inserting data from another table and data from textbox and checkbox to create a new record

I have to insert from table 1 into table 2 the values of username, name, lastname, roomnum and dormID.
I have to insert into table 2 the current date of today(it changes everyday), comments(the user wishes to enter- this is a textbox) and the attendance(present, absent, late)(these are the checkboxes).
When trying to click on the submit button the only thing that inserts into the database is the records that I am pulling from table1 into table 2.
When i try to incorporate to also insert the date, latecomments(textbox), and the attendance(checkboxes) it does not store any record.
This are the inserts:
$checkbox1 = $_POST['chk1'];
$latecomment=trim($_POST['latecomment']);
$d=strtotime("today");//todays date
$day=date("Y-m-d", $d);//date format
if($_POST["Submit"]=="Submit"){
for ($i=0; $i < sizeof ($checkbox1); $i++){
$query="Insert into dailyattendance (attendance) VALUES ('".$checkbox1[$i]."')";
mysql_query($query);
$daily=mysql_query("INSERT INTO dailyattendance(username, name, lastname, roomnum, dormID) SELECT user.username, user.name, user.lastname, user.roomnum, user.dormID FROM user WHERE user.role='Student'" );
$otherinfo=mysql_query("INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
}
}
There's a blank in your table name (in your given code):
INSERT INTO daily attendance
There's a WHERE clause in your INSERT statement and you are using UPDATE syntax with SET:
INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
Question: Is there a column named "attendance" in your table?
You should use only one INSERT statement if you want to add one row with all columns.
To clearify it a bit here is a code example you could start with. The SELECT on user is once before the loop because it seems to be same data all the time. You should add a function to escape strings before using them in the SQL statement to avoid errors when quotes are in it. Have a look at PHP or SQL error messages if something went wrong.
if($_POST["Submit"]=="Submit"){
$sql = "SELECT username, name, lastname, roomnum, dormID FROM user WHERE user.role='Student'";
$result = mysql_query($sql);
$student = mysql_fetch_assoc($result);
for($i=0; $i < sizeof ($checkbox1); $i++){
$sql = "INSERT INTO dailyattendance (username, name, lastname, roomnum, dormID, attendance, date, latecomment)";
$sql.= " VALUES ('".$student["username"]."', '".$student["name"]."', '".$student["lastname"]."', '".$student["roomnum"]."', '".$student["dormID"]."'";
$sql.= ", '".$checkbox1[$i]."', now(), '".$latecomment."')";
mysql_query($sql);
}
}

Two inserts in PHP/MySQL using LAST_INSERT_ID() and rows from another table

I am working on an events calendar using PHP and MySQL (V5.1) where the admin would add an event, and then an attendance list for that event would be created as well. I have three tables: events, attendance and members. So far I can create the event using information that is entered thorugh a PHP form. I'm trying to update the attendance table by inserting the event id from the event that has just been created, as well as pulling in the list of members (using their member ID) from the members table. Nothing is being added to attendance the table though. Can someone let me know what I should I be doing differently?
Some of the fields I am using in the tables:
Events: event_ID (Primary key, auto-increment), name, location, date
Attendance: attendance_ID (Primary key, auto-increment), event_ID, member_ID, attending
Members: member_ID (Primary key, auto-increment), name, email
enter code here
Here is the code:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT LAST_INSERT_ID(), members.member_ID FROM members");
if ($query1 and $query2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
You could use mysql_insert_id()
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$insert_id = mysql_insert_id() ;
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT {$insert_id}, members.member_ID FROM members") ;
A couple of important points. First, if you getting your last insert ID you should execute LOCK and UNLOCK queries first:
LOCK TABLES events WRITE;
UNLOCK TABLES
Second, you can use the mysqli_insert_id() method to get the ID of the last insert. This means that you must have an AUTO_INCREMENT field in the table you are inserting.
Put VALUES into $query2 to form a correct SQL-statement:
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) **VALUES (**SELECT LAST_INSERT_ID(), members.member_ID FROM members");

Categories