Hello,

I am developing and developed couple of websites in php succeccfully but many times I have seen a query a default function of php which i see in many tutorials it has been used but I am confused about it.

The function is mysqli_inser_id() I mean can anyone explain me what is the pupose and where we have to use it and where and when we need this function?

Thank You

Yes by viewing it generates ID which is created by the query but if we do not use this function the Auto Increment took place on every query though when ever a new record is added the id also increments is it true right this happens

So why we use this function ??

Member Avatar for diafol

It is used to give you the autoinc field value of the last record manipulated (update or insert). It can be useful if you want to insert data into more than one table. For example if you had this:

users: id | email | username | password

telephones: user_id | telno

If you had a form for adding a new user which had multiple form fields (unlimited) for telephones, you wouldn't store them all in the users table as it may violate 1NF (normalization), if, for example, you thought of storing telephone numbers as a comma separated string. So first you add data to the users table as usual, then, because you need the user_id you just created for adding telephone numbers to the telephones table, you need to call mysqli_insert_id() or the OOP equivalent.

Okay now I got it and the use of this function. Many times i do the same if there are two table having same id please correct me if I am wrong.

If I got two tables in my database
users
Orders

on both tables I have used a foreing key of user_id so I have to simply call a function of insert id right?

Member Avatar for diafol

Well, user_id with be a PK in your users table and an FK in your orders table. So, yes, it should be right.

Okay perfect thank you for the explanation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.