How to implement this relationship using PHP? - 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.

Related

PHP/MYSQL Selecting a MAX value and using it as an inserted value

I have a small database project using HTML forms and PHP code. It is working perfectly except the last part. Basically, I have my database connection setup and working in my PHP, and upon hitting the Add button it should insert values from the form to the database. My instructor said that due to table constraints it has to be inserted in a certain order, basically address table first and then staff table. IF I comment out the staff part of code, my successful confirmation page appears and the address appears in the database every time with an auto incremented address_id. The issue is that I'm supposed to query for a MAX(Address_id) and use that for inserting the staff part, as it uses address_id as a foreign key. When I do that, I get a foreign key constraint error on update cascade. If I completely pull out the INSERT staff code, and put a 'debug' to print the MAX(address_id), it prints correctly. I just can't get it to insert to the staff table correctly so that everything from my form creates a staff record. Here is the code:
$userQuery = "INSERT INTO address (address, district, city_id, postal_code, phone)
VALUES ('$address', '$district', '$city', '$postal_code', '$phone') ";
$addressResult = mysqli_query($connect, $userQuery);
if (!$addressResult)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
$maxQuery = "SELECT MAX(address_id) FROM address";
$result = mysqli_query($connect, $maxQuery);
$row = mysqli_fetch_assoc($result);
if (!$result)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
/**else
{
print ("<p>Average hourly wage:".$row['MAX(address_id)']."</p>");
}**/
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id)
VALUES ('$first_name', '$last_name', '$row', '$email', '$store_id')";
$staffResult = mysqli_query($connect, $userQuery1);
if (!$staffResult)
{
die("Could not successfully run query ($userQuery1) from $db: " .
mysqli_error($connect) );
}
else
{
print(" <h1>New Staff Record Added!</h1>");
print ("<p>The following record was added:</p>");
print("<table border='0'>
<tr><td>First Name</td><td>$first_name</td></tr>
<tr><td>Last Name</td><td>$last_name</td></tr>
<tr><td>Email</td><td>$email</td></tr>
<tr><td>Store ID</td><td>$store_id</td></tr>
<tr><td>Address</td><td>$address</td></tr>
<tr><td>City</td><td>$city</td></tr>
<tr><td>District</td><td>$district</td></tr>
<tr><td>Postal Code</td><td>$postal_code</td></tr>
<tr><td>Phone</td><td>$phone</td></tr>
</table>");
}
You are not calling the correct associative index. You are just calling the array:
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id) VALUES ('$first_name', '$last_name', '{$row['MAX(address_id)']}', '$email', '$store_id')";

Grab Record ID before during submit and save to another table

I have two tables:
Invoices & Invoices Parts
The reason i'm using two tables is because i dont want to save the invoice parts array into one record on the Invoices table and i dont want to save it into multiple records on the Invoices table.
When i submit the data into both tables, how can i link both tables together with the ID if i dont have the ID yet?
$result = mysqli_query($mysqli, "INSERT INTO invoices(labelwarning, status, todaysdate, todaystime, todaysdatetime, avatar, firstname, lastname, mwaid, nextgenid, manager, manageremail, dispatcher, dispatcheremail, techemail, tag, serialnumber, currentequipment, company, address, city, state, zip, contactperson, contactnumber , currentdate, timearrived, timecompleted, login_id) VALUES('$labelwarning', '$status', '$todaysdate', '$todaystime', '$todaysdatetime', '$avatar', '$firstname', '$lastname', '$mwaid', '$nextgenid', '$manager', '$manageremail', '$dispatcher', '$dispatcheremail', '$techemail', '$tag', '$serialnumber', '$currentequipment', '$company', '$address', '$city', '$state', '$zip', '$contactperson', '$contactnumber ', '$currentdate', '$timearrived', '$loginId')");
$result2 = mysqli_query($mysqli, "INSERT INTO invoiceparts(partnumber, partdescription, partprice, partquantity, partdb, login_id) VALUES '$partnumberstring', '$partdescriptionstring', '$partpricestring', '$partquantitystring', '$partdbstring', '$loginId')");
If you need to link the "login_id" and the login_id is generated with AUTO_INCREMENT then you can do it by
for Mysqli connection, mysqli_insert_id($mysqli);
for PDO connection, $mysqli->lastInsertId();
If the login_id is not an AUTO_INCREMENT field then you can do it by
SELECT login_id FROM invoices ORDER BY login_id DESC LIMIT 1;
It'll return the last inserted row from there we can fetch the login_id

Obtain UserID after inserting new record

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

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!

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

Categories