I have a parent and child form, with the child form connected to the parent form by the parent_id. The forms are on different pages, and i am trying to pass the id of the parent form to the child form using session variables.

What ive done (with no luck) is start a session after a parent entry is inserted into the database and store the id of the parent as a variable.

$query = "INSERT INTO parent (id, parent_name) VALUES ('','$parent_name')"; 
$result = mysql_query($query) or  die(mysql_error());  
$id = $_SESSION['id'];

And try to pass the session variable into the child table by calling the variable in the child form, and insert it into the parent_id field of the child form:



<form enctype="multipart/form-data" name="" action="" method="POST">		
<table width="400" border="0"> 

  <td valign="top"><label for="parent_id"> Parent_id </label></td>	
  <td><input type="text" name="parent_id" id="parent_id" value="<?php echo $id ?>"/>	</td>	

  <td valign="top"><label for="id"> Child</label></td>	
  <td><input type="text" name="id" id="id" /> </td>	


I'm wondering maybe if i need to retrieve the parent_id first with a SELECT query before i start the session? If so, how i do make sure i'm retrieveing the parent that was just inserted? Any hints will be appreciated. Thanks

6 Years
Discussion Span
Last Post by ayooshkasmth

you do it wrong!

$id = 020303;
$query = "INSERT INTO parent (id, parent_name) VALUES ('$id','$parent_name')"; 
$result = mysql_query($query) or  die(mysql_error());  

Yes, you would need to retrieve the ID from the table. To do this you can use mysql_insert_id() .
A couple of tips: session_start() should be at the top of your script.
If your table has 'id' set to AUTO_INCREMENT, you can re-write line 1 as

$query = "INSERT INTO parent (parent_name) VALUES ('$parent_name')";

Your line 6 doesn't really make sense. I think you meant $_SESSION['id'] = $id; . But even then, $id doesn't have a value. You need to retrieve it from the DB:

$_SESSION['id'] = mysql_insert_id();

Then on line 4 of the second block of code, you have just $_SESSION['id'] , but it's not doing anything there. Also you're missing a semi-colon on that line.

Edited by EvolutionFallen: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.