How to input values into database and collect the new id to store in php/html?
I just can't figure out how to solve this problem using php to show on a web page.
- When a user inputs values into "navn" and "kommentar" on my webpage. I will save these into two values. The "navn" value shall be saved into the database table "bruker" where "bruker_id" is auto increment. Then I want to get back which bruker_id the "navn" was saved under.
--> INSERT INTO bruker (navn) VALUES (inserted name from user);
- Using the "bruker_id" and the "kommentar" I want to save into the table "kommentar" all the relevant information. Timestamp shall be current time and attraksjons_id is saved in a URL parameter called attraksjoner in Dreamweaver.
--> SELECT bruker.bruker_id FROM bruker WHERE bruker.navn = inserted name from user; --> INSERT INTO attraksjon (bruker_id, attraksjons_id, kommentar, tidsstempel) VALUES (collected bruker_id from user, URL parameter attraksjoner from dreamweaver, comment collected from form, automated timestam);
Thank you in advance for your answer.
My database is as following:
Tablenavn: attraksjon Primary key: attraksjons_id attributes: attraksjons_navn, generell_info
---- Relation many-to-many table ----
Created many-to-many table reisetips, primary keys: bruker_id, attraksjons:id attributes: kommentar, tidsstempel
--- Next tabel which is connected to attraksjon with many-to-many relation ---- Table name: kommentar Primary keys: bruker_id attributes: navn
My form consists of a text field for "navn" and one text area for "kommentar".
Answer
Solution:
The Mysqli function "insert_id" can be helpfull in your case. As described by the documentation : PHP Documentation
Another way to achieve this is by not using auto_increment and manage the ID yourself: Before Inserting into the database your row, grab the last ID in the table and add one (For Exemple). Pay attention that to avoid lock and other concurent write, you'll have to do this using transaction and prepared statement.
Answer
Solution:
if you are using PDO then PDO::lastInsertId will do the work