insert into multiple tables linked by foreign keys (PHP, MySQL)

Thread Solved

Join Date: Aug 2009
Posts: 31
Reputation: AdventDeo is an unknown quantity at this point 
Solved Threads: 0
AdventDeo AdventDeo is offline Offline
Light Poster

insert into multiple tables linked by foreign keys (PHP, MySQL)

 
0
  #1
Aug 31st, 2009
Hello,

I've read on how to insert properly into two linked tables using mysql_insert_id() function from:
http://www.webproworld.com/web-progr...unique-id.html

now how about if i want it to be from 4 linked tables? can I still use the function? and I want some to be a dropdown lists.

My tables are:
Client(clientID, Name, Address, ContactNo, countryID*, supportID*)
Environment(environmentID, environmenttypeID, Hostname, ClientID)
Environenttype(environmenttypeID, Type)
System(systemID, Label, environmentID)

Note:
-*ignore these fields for this thread
-all IDs are auto_inc int except for environment type
-There are only 3 fixed environment types:
--------id--------|-------type------
--------P--------|----Production--
--------T--------|--------Test------
--------D--------|--------DR--------

And I want my form to be in one page like:

------Client------
Select clients' name: [drop-down box here|v|]
(other fields like address and contact will be echoed here based on the name selected)
------Environment------
Type: [show environmenttype.type where environmenttype.id=environment.id(drop-down box)|v|]
Hostname: [enter text]
------System------
Label: [enter text]

[Back] [Submit]


and after the user submits, they will be redirected to another page where they'll insert more data to other tables inside the db based on the id of the system submitted here. but i guess that's a different thing altogether.

Please help me in giving some light as to how to make this input form. Thank you so much!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 1,078
Reputation: ardav will become famous soon enough ardav will become famous soon enough 
Solved Threads: 137
ardav's Avatar
ardav ardav is offline Offline
Veteran Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
-1
  #2
Aug 31st, 2009
I don't understand what you want to achieve with mysql_insert_id.

Creating the form shouldn't use mysql_insert_id.

If you need to get data into dropdown that comes from more than one table, use INNER JOINs, e.g.

  1. SELECT table1.field2 AS id, table1.field8 AS name, table2.field3 AS label, table2.field4 AS confirm FROM table1 INNER JOIN table2 ON table1.field1 = table2.field2 WHERE table1.field4 = 'test'

The 'while loop' will then allow you to populate the option tags in your select widget (dropdown).

  1. <?php
  2.  
  3. ...(previous mysql code and retrieval)...
  4.  
  5. //assume $result is your resultset from mysql_query()
  6.  
  7. while($data = mysql_fetch_array($result)){
  8. $label = stripslashes($data['label']);
  9. $option .= "\n\t<option id="{$data['id']}">{$label}</option>";
  10. }
  11. ?>
  12.  
  13. <select id="tractors">
  14. <?php echo $option; ?>
  15. </select>

The above code joins info from 2 tables into the dropdown options. Personally, I'd place all the php routines above the DTD unless you're using a templating system like Smarty etc.

Check out the usage of INNER JOINS in the mysql user manual for more complicated scenarios.
Happy Humbugging Christmas
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 1,078
Reputation: ardav will become famous soon enough ardav will become famous soon enough 
Solved Threads: 137
ardav's Avatar
ardav ardav is offline Offline
Veteran Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
-1
  #3
Aug 31st, 2009
Oh for goodness sakes!! I did it agin. I'm forever using 'id' instead of 'value' in my option elements.

Please change:
  1. $option .= "\n\t<option id="{$data['id']}">{$label}</option>";
to:
  1. $option .= "\n\t<option value="{$data['id']}">{$label}</option>";
Happy Humbugging Christmas
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 31
Reputation: AdventDeo is an unknown quantity at this point 
Solved Threads: 0
AdventDeo AdventDeo is offline Offline
Light Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
0
  #4
Aug 31st, 2009
Okay, maybe I'm not clear enough and I apologize...

I want to make a form where user can input the information they want to add into the database... i need to use the mysql_insert_id() because of the foreign keys I have to assign automatically...

I think this should clarify things...
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 1,078
Reputation: ardav will become famous soon enough ardav will become famous soon enough 
Solved Threads: 137
ardav's Avatar
ardav ardav is offline Offline
Veteran Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
-1
  #5
Sep 1st, 2009
and after the user submits, they will be redirected to another page where they'll insert more data to other tables inside the db based on the id of the system submitted here. but i guess that's a different thing altogether.
OK, that is a different ask.

The fact that you're asking the user for hostname and system label will cause problems. Perhaps these should be provided in a dropdown?

Because you're doing this the environment table data and the system table data are directly linked to the client via 1:1 relationship. The data in these tables is not available to other clients, therefore I fail to see why they are in a separate table.

A healthier table would be (IMO):

CLIENT
clientID, Name, Address, ContactNo, countryID*, supportID*, environmenttypeID, Hostname, Label)

ENVIRONMENTTYPE
Environenttype(environmenttypeID, Type)

I don't think that you gain anything from the two other tables, as the data is unique to the client and to each other (1:1). I don't know if I'm making sense to you.

In this way you'll cut down on the complexity of your db and form.
Happy Humbugging Christmas
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 31
Reputation: AdventDeo is an unknown quantity at this point 
Solved Threads: 0
AdventDeo AdventDeo is offline Offline
Light Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
0
  #6
Sep 1st, 2009
Mmm.. Actually one client will have 3 Environments named Production, Test, and DR... and each Environment can have many Systems... e.g. Client 1 Production sys 1, Client 1 Production sys 2, etc..

Hence am pretty sure my relational table are fine...

Anw, I got the thing solved using session handling... thank u anw for ur time to reply me! =)

Here's the 3 files (quite long so don't bother if you don't wanna read) just for reference. Am not closing this thread yet, though, as am opening the possibility of people giving me feedback on how I can improve my codes:

addenvform.php

  1. <?php session_start(); ?>
  2.  
  3. <html>
  4. <head>
  5. </head>
  6.  
  7. <body background = "background.gif">
  8. <center>
  9.  
  10. <table style="width:902px;margin-top:0px;margin-bottom:0px;background-color:#fff9e3;border="0" cellpadding="0" cellspacing="0">
  11. <tr><td align="center"><a name="top"></a>
  12. <img style="margin-top:0px" border="0" src="thomson_reuters_logo.gif" width="500" height="104">
  13. </td></tr>
  14. </table>
  15.  
  16. <hr />
  17.  
  18. <fieldset>
  19. <legend>
  20. Record New Environment:
  21. </legend>
  22.  
  23. <form name=sel>
  24. <table>
  25. <tr><td align="left">Country:</td>
  26. <td><font id=country><select>
  27. <option value='0'>=================</option>
  28. </select></font></td>
  29. </tr>
  30. <tr><td align="left">Client:</td>
  31. <td><font id=client><select>
  32. <option value='0'>=================</option>
  33. </select></font></td>
  34. </tr>
  35. </table>
  36. </form>
  37.  
  38. <form method="post" action="addenvsubmit.php">
  39. <table>
  40. <tr><td align="left">Environment:</td>
  41. <td><input type="text" name="env" size="20"></td>
  42. </tr>
  43. <tr><td colspan="2">
  44. <p align="center">
  45. <input type="submit" value="Enter record">
  46. </td></tr>
  47. </table>
  48. </form>
  49.  
  50. </fieldset>
  51.  
  52.  
  53. </center>
  54. </body>
  55. </html>
  56.  
  57. <script language=Javascript>
  58. function Inint_AJAX() {
  59. try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
  60. try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
  61. try { return new XMLHttpRequest(); } catch(e) {}
  62. alert("XMLHttpRequest not supported");
  63. return null;
  64. };
  65.  
  66. function dochange(src, val) {
  67. var req = Inint_AJAX();
  68. req.onreadystatechange = function () {
  69. if (req.readyState==4) {
  70. if (req.status==200) {
  71. document.getElementById(src).innerHTML=req.responseText;
  72. }
  73. }
  74. };
  75. req.open("GET", "addenvdropdown.php?data="+src+"&val="+val);
  76. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1");
  77. req.send(null);
  78. }
  79.  
  80. window.onLoad=dochange('country', -1);
  81. </script>
  82.  

addenvdropdown.php

  1. <?
  2. session_start();
  3.  
  4. header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  5. header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  6. header ("Cache-Control: no-cache, must-revalidate");
  7. header ("Pragma: no-cache");
  8.  
  9. header("content-type: application/x-javascript; charset=tis-620");
  10.  
  11. $data=$_GET['data'];
  12. $val=$_GET['val'];
  13.  
  14. include 'config.php';
  15. include 'opendb.php';
  16.  
  17. if ($data=='country') {
  18. echo "<select name='country'
  19. onChange=\"dochange('client', this.value)\">\n";
  20.  
  21. echo "<option value='0'>Select Country</option>\n";
  22.  
  23. $result=mysql_query("SELECT c.`Country ID`, c.`Name`
  24. FROM clientconfiguration.country c
  25. ORDER BY c.`Name`")
  26. or exit (mysql_error());
  27.  
  28. while(list($id, $name)=mysql_fetch_array($result)){
  29. echo "<option value=\"$id\" >$name</option> \n" ;
  30. }
  31. } else if ($data=='client') {
  32. echo "<select name='client'
  33. onChange=\"dochange('env', this.value)\">\n";
  34.  
  35. echo "<option value='0'>Select Client</option>\n";
  36.  
  37. $result=mysql_query("SELECT cl.`Client ID`, cl.`Name`
  38. FROM `client` cl, country co
  39. WHERE cl.`Country ID` = co.`Country ID`
  40. AND cl.`Country ID` = '$val'
  41. ORDER BY cl.`Name`")
  42. or exit(mysql_error());
  43.  
  44. while(list($id, $name)=mysql_fetch_array($result)){
  45. echo "<option value=\"$id\" >$name</option> \n" ;
  46. }
  47. } else if ($data=='env') {
  48. echo "<select name='env'>\n";
  49.  
  50. $_SESSION['envid']= $val;
  51.  
  52. }
  53.  
  54. echo "</select>\n";
  55.  
  56. include 'closedb.php';
  57.  
  58. ?>

addenvsubmit.php

  1. <?php
  2.  
  3. session_start();
  4.  
  5. include 'config.php';
  6. include 'opendb.php';
  7.  
  8. $envid = $_SESSION['envid'];
  9.  
  10.  
  11. $sql="INSERT INTO Environment
  12. VALUES (NULL, NULL, '$_POST[label]',".$envid.")";
  13.  
  14. if (!mysql_query($sql))
  15. {
  16. die('Error: ' . mysql_error());
  17. }
  18.  
  19. echo "1 record added";
  20.  
  21.  
  22. include 'closedb.php';
  23. session_destroy();
  24.  
  25. ?>
Last edited by AdventDeo; Sep 1st, 2009 at 10:23 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 1,078
Reputation: ardav will become famous soon enough ardav will become famous soon enough 
Solved Threads: 137
ardav's Avatar
ardav ardav is offline Offline
Veteran Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
-1
  #7
Sep 2nd, 2009
Ok, didn't realise you could have multiple entries for a client. This wasn't obvious from the form.

My solution is still relational but can't do what you want.

I don't have the time at the moment to look at the code, but I hope to get back to you later.
Happy Humbugging Christmas
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 1,078
Reputation: ardav will become famous soon enough ardav will become famous soon enough 
Solved Threads: 137
ardav's Avatar
ardav ardav is offline Offline
Veteran Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
-1
  #8
Sep 2nd, 2009
If you've got a login form where a client's details are checked you could get the client_id and client name and place that into session variables, to be used in the form.

I'd use a single form to add new environments (host, system) and not bother with ajax.

  1. <?php
  2. ...(retrieve environment type data from db - in $result)....
  3. while ($data = mysql_fetch_array($result)){
  4. $envoptions .= "\n\t\t<option value='{$data['id']}'>{$data['type']}</option>";
  5. }
  6. ?>
  7.  
  8. <form ....>
  9. <p>Name: <?php echo $_SESSION['client_name'];?></p>
  10. <input type="hidden" value="<?php echo $_SESSION['client_id'];?>" id="id" name="id" />
  11. <label for="envtype">Environment type:</label>
  12. <select id="envtype" name="envtype">
  13. <?php echo $envoptions;?>
  14. </select>
  15. <label for="host">Hostname:</label>
  16. <input id="host" name="host" type="text" />
  17. <label for="system">System:</label>
  18. <input id="system" name="system" type="text" />
  19. <input type="submit" id="subrec" name="subrec" value="Enter record">
  20. </form>

This should give you all the ids required to update all the various tables via $_POST array.
Last edited by ardav; Sep 2nd, 2009 at 12:56 pm.
Happy Humbugging Christmas
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 31
Reputation: AdventDeo is an unknown quantity at this point 
Solved Threads: 0
AdventDeo AdventDeo is offline Offline
Light Poster

Re: insert into multiple tables linked by foreign keys (PHP, MySQL)

 
0
  #9
Sep 3rd, 2009
Hey thanks alot dude! I shall mark this a solved! =)
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the PHP Forum
Thread Tools Search this Thread



Tag cloud for PHP
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC