#native_company# #native_desc#
#native_cta#

Working With Related Tables

By Chris Goranson
on June 28, 2000

Version: 1.1

Type: Sample Code (HOWTO)

Category: Other

License: GNU General Public License

Description: This is a pretty simple little snippet, but it helped me understand how to use relational tables w/in PHP.

/* Substitute appropriately w/in your own code...
1st table is the table that contains a related field to the 2nd.
For example, the first table would have an auto increment
field like address_record_id, int(11), PRI, 0.  The 2nd table would
have a field address_record_id, int(11), NULL.  The mysql_insert_id
command gets the $addressid variable ready for the second INSERT. */

else    
	{
	if (!($newresult = mysql_db_query($DB, "INSERT INTO your1sttable (address1,address2,city,state) 
	VALUES ('".addslashes($form_address_line1)."','".addslashes($form_address_line2)."','".addslashes($form_city)."','".addslashes($form_state)."')"))) 
                // Displays error message if INSERT fails.
                {
                DisplayErrMsg(sprintf("internal error %d:%sn", 
                mysql_errno(), mysql_error()));
                exit();
	        }
                    /* Grabs last row from the above insert, uses that as
                    the related value.  NOTE:  If the value is an INT in
                    your table, dont use addslashes, as with the example
		    below. */

                    $addressid = mysql_insert_id($newresult);
                    if (!($newresult = mysql_db_query($DB, "INSERT INTO your2ndtable (user_name,login_name,password,email_id,address_record_id) 
				      VALUES ('".addslashes($form_name)."','".addslashes($form_user_id)."','".addslashes($form_password)."','".addslashes($form_email_id)."','$addressid')"))) 
                 // Displays error message if INSERT fails.           
                 {
                 DisplayErrMsg(sprintf("internal error %d:%sn", 
                 mysql_errno(), mysql_error()));
                 exit();
	         }
                      
                      
                      else 
                      {
                      header("Location:http://$HTTP_HOST/$DOCROOT/success.htm");
                      exit(); 
                      }
	}

// The last else just directs the user to a page confirming everything went ok.