Reputation: 587
I want to make a basic forum for my website. I have 2 tables for this:
table topics: fields id, title
table posts: fields id, topicid, message
When a user want's to create a topic he has to complete a form with topic title and message. The title will be inserted in the topics table and the message in the posts table, but I will need topicid (field id in topics table) for the second insert.
INSERT INTO topics (title) VALUES ('$title')
INSERT INTO posts (topicid, message) VALUES ('???', '$message')
How can I get the topicid?
Upvotes: 0
Views: 51
Reputation: 4974
Mysql:
INSERT INTO topics (title) VALUES ('$title')
INSERT INTO posts (topicid, message) VALUES (LAST_INSERT_ID(), '$message')
Or with PHP:
[...]
// Connect to mysql
$title = 'Foo';
$message = 'Bar';
mysql_query('INSERT INTO topics (title) VALUES (' . $title . ')');
mysql_query('INSERT INTO posts (topicid, message) VALUES (' . mysql_insert_id() . ', ' . $message . ')');
Upvotes: 2