How to insert a table column value into another table column

Ask about a PHP problem here.
Post Reply
brisk
Posts: 26
Joined: Mon Nov 21, 2011 1:22 am

How to insert a table column value into another table column

Post by brisk »

Feel like this so bloody easy but I can't figure it out :-S

So I have a submit button which gives a couple of columns some data but then the ID column is left alone as it is auto incremented. However I then need a statement after taking that automatic incremented ID column value and put it in another table. See below:

I need each ID value that is generated in the table 'threads' and also put into the table 'thread_likes' which has the column name thread_id. You can seem I'm missing the last value as I'm unsure what to put :-S
else{						
		connect();
		selectDB();		
		
		mysql_query("INSERT INTO threads SET fact='$fact', user_id='$username',date_posted=NOW(), type='$type'");	
		$query2 = mysql_query("UPDATE users SET thread_count=thread_count+1 WHERE username='$username'");
		$query3 = mysql_query("INSERT INTO thread_likes (status, username, thread_id) VALUES (0, $username,  )");
		
		echo 'FACT has been posted. <a href = "facts.php">Return.</a>';	
		}
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: How to insert a table column value into another table co

Post by Temor »

the function mysql_insert_id() returns the last inserted ID. Maybe that's what you're looking for?

http://php.net/manual/en/function.mysql-insert-id.php
brisk
Posts: 26
Joined: Mon Nov 21, 2011 1:22 am

Re: How to insert a table column value into another table co

Post by brisk »

Temor wrote:the function mysql_insert_id() returns the last inserted ID. Maybe that's what you're looking for?

http://php.net/manual/en/function.mysql-insert-id.php
YESYYESYSEYSEYSESEYES THAT'S IT, IT WORKS!!!

OMG THANKS!!!
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: How to insert a table column value into another table co

Post by Temor »

You're welcome :lol:
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: How to insert a table column value into another table co

Post by jacek »

There is also an SQL function which you can use directly in the query
INSERT INTO thread_likes (status, username, thread_id) VALUES (0, $username,  LAST_INSERT_ID())
Does basically the same thing, but will save you a call to the database.
Image
Post Reply