Hi, i'm having a little problem with my php script. Here's the deal. I have 2 tables and I want to assign a post variable to a row in one table and then insert the id value of that table in another table. The script is as follows:

clients.php

<?php include "includes/config.php"; ?>
<?php 
 //initialize the session
if (!isset($_SESSION)) {
  session_start();
}
if ( !isset( $_SESSION['loggedUserID'] ) ) { // user is not logged in
  header( 'Location: login.php' ); // redirect to login.php
}
if (isset($_POST['add'])) {
    //this is where the issue is
    $agentName = mysql_real_escape_string($_POST['agentName']);
...
$sql = "INSERT INTO tblpolicydetails (..., agentID , ...)  
        VALUES( ..., '$agentName', ... )";
...
<script>
// some AJAX for autocomplete for textbox "agentName"
</script>
<body>
<form ...>
 <p>Agent Name
<input type="text" name="agentName" ...//Some event handlers for this textbox>
...
<input type="submit" name="add" >
</form>
</body>

Now the issue is that there is a record in tblagents(not in code) with agentID = 5 say, so when i click in the "agentName" textbox an autocomplete function populates the textbox with name and surname of agent with agentID = 5 from tblagents. When i press submit i want the agentID from tblagents to be inserted into tblpolicydetails and not the name of the agent. Both tables have column name agentID.

I know there is some vital php code needed for this to work, so please help me out. Thanx in advance.

I assume you are looking for this: mysql_insert_id

Well it seems that the mysql_insert_id() function only returns the AUTO_INCREMENT ID from the previous INSERT operation, whereas i want a specifically chosen id. Please correct me if i'm wrong.

Oh, misunderstood then. If you have the agentId, then you can store it in a hidden input, so it will be sent when the form is submitted.

Otherwise you'll have to do a database lookup to find the agentId belonging to the agentName.

So will i be able to insert the agentID from agents table corresponding to the agent name selected in the textbox to the other table(tblpolicydetails) using hidden form fields?

hidden fields are not actually hidden.you can see its value in source code.better store it in session variables.

Ok i took your advice about session variables and it's now working. Thanks a lot.

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.