How to input values into database and collect the new id to store in php/html?

267

I just can't figure out how to solve this problem using php to show on a web page.

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

  1. 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".

413

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.

345

Answer

Solution:

if you are using PDO then PDO::lastInsertId will do the work

People are also looking for solutions to the problem: php - Installing specific laravel version with composer create-project

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.