Obtain UserID after inserting new record - php

I am currently working with a form where you are able to create new users. You would specify the username, firstname, etc and a new record would be inserted into the Users table in a database.
Right after the creation of an user more steps follow, but for these having the auto generated UserID in the session would be very useful.
How can I accomplish this? I tried the following:
sqlsrv_query($conn1,"INSERT INTO Users (Username, Firstname, Lastname, JobTitle)
VALUES ('$_POST[Username]', '$_POST[Firstname]', '$_POST[Lastname]', '$_POST[JobTitle]'); SELECT SCOPE_IDENTITY() AS UserID;");
$result = sqlsrv_query($conn1); $next_result = sqlsrv_next_result($result); $row = sqlsrv_fetch_array($result);
$_SESSION['UserID'] = $result;

Use OUTPUT INSERTED in your query.
Change Your Code Like,
$result = sqlsrv_query($conn1,"INSERT INTO Users
(Username, Firstname, Lastname, JobTitle) OUTPUT INSERTED.UserID
VALUES ('$_POST[Username]', '$_POST[Firstname]', '$_POST[Lastname]', '$_POST[JobTitle]');
and you will get last inserted id in $result

Related

Return the ID of the last value inserted SQL

I'm inserting data into members table, after I've inserted it I want to get the userID of the information just inserted. Whats the best way about doing this ?
My php code
//Insert info into database
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')";
//Run a query to check if data has been inserted correctly.
$records = mysqli_query($connect, $sql);
I did try this SQL but was getting errors
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')"; SELECT SCOPE_IDENTITY(userID);
Assuming $connect as the variable holding your connection information, which seems legit, you can get the value of the last id with:
$user_id = mysqli_insert_id($connect);
This is something you can do from the PHP MySQLi interface, rather than directly from SQL!

Last id get using php oracle

I want to get the last id inserted but i don;t know how to get it in oracle. Any help will be appreciated. Below is my query.
$query = oci_parse($con,"INSERT INTO USER_LOGIN (USERNAME, PASSWORD, CNIC, ROLE_ID, PICTURE)
VALUES ('$Username', '$Password', '$CNIC', '$Role', '$Filename')");
Get above id: (don't know)
$OK = oci_parse($con,"SELECT LAST_INSERT_ID() FROM USER_LOGIN");
oci_execute($OK);
$row = oci_fetch_array($OK, OCI_ASSOC + OCI_RETURN_NULLS);
if($row)
{
$USERID = $row['USER_ID'];
}
It's not clear what you are trying to achieve (see Justin's questions). But if you want the trigger populated id of the user_login table back to your code you can use the returning clause.
$query = oci_parse($con,"INSERT INTO USER_LOGIN (USERNAME, PASSWORD, CNIC, ROLE_ID, PICTURE)
VALUES ('$Username', '$Password', '$CNIC', '$Role', '$Filename')
RETURNING YOUR_ID
INTO :LAST_INS_ID");
oci_bind_by_name($query, ':LAST_INS_ID', $theNewID, 8);

PHP - MySQL find row and replace

what im trying to figure out is how do i find something in my MySQL database and then replacing another row. Example
mysqli_query($con,"INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$_POST[custom]', '$_POST[receiver_email]','$_POST[mc_gross]')");
$result = mysqli_query($con,"SELECT * FROM Persons
WHERE FirstName='bjarne'");
mysqli_query($con,"INSERT INTO persons (LastName)
VALUES ('$_POST[item_name]')");
Here i would like it to find where FirstName is "bjarne" and then replace his LastName with '$_POST[item_name]' in this case.
Try this:
$result = mysqli_query($con,"UPDATE `Persons` SET `LastName`='".$_POST['item_name']."'
WHERE `FirstName`='bjarne'");

storing session data to mysql tables and last_insert_id function

When a nurse logs into the patient system, details about her are stored in session variables - including her user id. I have created a registration script so that when the nurse registers a new patient, her id is stored in the super column of the user table. This is so the patient can be allocated to her only.
The problem is that when I run the insert statement, the value 0 is stored in the super user column instead of the user id of the nurse. How can this be solved?
I have a profile table that has the profile of the user and it links to the user table. I have used the first insert statement to create the record in the user table. I want the second statement to create a record in the profile table with the profile id being the same as the newly created user_id. I am trying to use the LAST_INSERT_ID() function, but it too is storing 0 and not the last id.
Here is my code around the specific part in question. I am sorry if the formatting is not correct. I am using a screen reader and the formatting options on this website arn't very accessible to me.
I have stored the form data from $_post into all the variables used below.
$SuperUser = $_SESSION['SuperUser'];
//insert query for user table
$UserInsert = "insert into user
(User_id,
Username,
Password,
User_level,
SuperUser)
values(null,
'$Username',
'$Password',
'1',
'$SuperUser')";
//run query for inserting data for user table
mysql_query($UserInsert) or die("cannot insert into user");
//Select the last increment id from user table
$LastIdQuery = "Select LAST_INSERT_ID()";
$LastId = mysql_query($LastIdQuery) or die("Cannot select last id");
//insert query for profile table
$ProfileInsert = "insert into profile
(User_id,
FirstName,
LastName,
Dob,
NI_Number,
NHS_Number,
Address1,
Address2,
Town,
Postcode,
Email,
Contact_Number,
Comments)
values('$LastId',
'$FirstName',
'$LastName',
'$DobYear-$DobMonth-$DobDay',
'$NI_Number',
'$NHS_Number',
'$Address1',
'$Address2',
'$Town',
'$Postcode',
'$Email',
'$Contact_Number',
'$Comments')";
//insert into profile
mysql_query($ProfileInsert) or die("Unable to insert in profile");
mysql_close();
Try doing $id = mysql_insert_id() instead of the LAST_INSERT_ID function that you're doing. Also, if you're storing the mysql connection in a variable, passing it to mysql_insert_id() can make it more accurate. E.g when connecting to database:
$link = mysql_connect(......);
then later:
mysql_query($ProfileInsert) or die("Unable to insert in profile");
$id = mysql_insert_id( $link );
mysql_close( $link );

How to implement this relationship using PHP?

ERD diagram
PHP code:
$insert_address = "insert into address (Street, Town, County, Postcode) values('$street', '$town', '$county', '$postcode')";
$run_address = mysqli_query($con, $insert_address);
$last_id = mysqli_insert_id($con);
$insert_user = "insert into user (UserIPAddress, Username, Email, Forename, Surname, Password, UserIcon, AddressID) values('$IP', '$username', '$email', '$firstname', '$secondname', '$password', '$userimage', '$last_id')";
$run_user = mysqli_query($con, $insert_user);
$sel_cart = "select * from cart where IPAddress='$IP'";
$run_cart = mysqli_query($con, $sel_cart);
$check_cart = mysqli_num_rows($run_cart);
In order for the AddressID to automatically populate my user table, I need to run the query before I run the insert query for my user table. However, inserting the 'UserID' into the address table requires the insert user query to have been run before the insert address query. I can't run two queries in one, so I deleted the UserID field from my Address table.
However, now I need the user to be able to update the details stored in the database tables. This works fine for the info in the user table, but not for the info in the address table. To combat this, I created a separate html page where the user could update their address, but without the userID I don't know how to get the right address for each user.
I'm up to
$get_address = "select * from address where AddressID='$address'";
But this obviously doesnt work.
Without the foreign key UserID I don't know how to make it work.
I've tried sessions but I really don't understand them.

Categories