Creating an id number?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
cturner
Forum Contributor
Posts: 153
Joined: Sun Jul 16, 2006 3:03 am
Location: My computer

Creating an id number?

Post by cturner »

I am wanting to create an id number and then add to a database table. The reason why I am wanting to do this is because I want the user to add a comment then when that is done I want a id number to be added to each of two tables so it can be retrieved when the comments for a particular article are being viewed. Can someone please show me how I can do this? Thanks in advance.
User avatar
wtf
Forum Contributor
Posts: 331
Joined: Thu Nov 03, 2005 5:27 pm

Post by wtf »

select max(id) will return the largest id from the database you can just add 1 to it for the next available
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

wtf wrote:select max(id) will return the largest id from the database you can just add 1 to it for the next available
In this case you have to lock the table or you will get a race condition.
You should let the database handle such ids. What database system or abstraction layer do you use?
User avatar
cturner
Forum Contributor
Posts: 153
Joined: Sun Jul 16, 2006 3:03 am
Location: My computer

Post by cturner »

volka and wtf I have looked at what you have posted and it will help but I am wanting to create the id number before I have to retrieve it from the database table. How do I create the id number? I am using mysql.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Why do you want to create this id before you have inserted any data?
User avatar
cturner
Forum Contributor
Posts: 153
Joined: Sun Jul 16, 2006 3:03 am
Location: My computer

Post by cturner »

So I know which comment belongs to which article.

Is this the right way to do it?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

First there is the article, this article has an id, let's call the field article_id.
Now someone wants to write a comment for this article. This is probably signaled by pressing some kind of button or link
article:
yadda yadda yadda
[click here to comment this article]
Here you already need to know the article_id or you won't know for which article the button was pressed.
Make article_id an auto_incrment field. If you need to know the value right after an INSERT statement use e.g. http://de2.php.net/manual/en/function.m ... ert-id.php
Post Reply