Hi,

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());  
 
session_start();
$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:

<?php 

session_start();  
$_SESSION['id'] 

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

<tr>	
  <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>	
</tr> 

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

</table>
</form>	
?>

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

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());  
 
session_start();
$_SESSION['id']=$id;

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.