Page 1 of 1

How to insert a table column value into another table column

Posted: Sun Mar 25, 2012 2:59 pm
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>';	
		}

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

Posted: Sun Mar 25, 2012 3:24 pm
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

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

Posted: Sun Mar 25, 2012 3:54 pm
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!!!

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

Posted: Sun Mar 25, 2012 4:08 pm
by Temor
You're welcome :lol:

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

Posted: Tue Mar 27, 2012 5:29 pm
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.