0

I created a HTML form with one drop down listing of items from postgresql database, I wish to have some of the fields in the form to populate automatically from the database when an item is selected from the dropdown menu. I also have some other fields on the form which needs to be filled-in by the users before pressing the submit button to push the entire data back to the database.

Currently my script is not able to connect to the database or populate the drop-down listing on the form and also not able to autopopulate the other specified form fields (which are the attributes of the items in the dropdown list also stored in the database) and the second issue im also having is that after entering data into the input fields and click submit. it creates a new record in the database instead of populating the required columns in the database. Can Someone please take a look at my script and help me out.

Here is the script to create the data entry form with a dropdown

 <?php
//Php Code to connect to postgresqldatabase
$PGHOST = "localhost:25376";
$PGDATABASE = "Pipeline";
$PGUSER = "postgres";
$PGPASSWORD = "Casa2009";
$PGPORT = 5432;
$db_handle = pg_connect("dbname=$PGDATABASE user=$PGUSER password=$PGPASSWORD");


//<!-- #2 -->
 if(isset($_POST['submit_1'])){
 //Code to post fieldtally data to the database
 $pipeno = pg_escape_string( $_POST['pipeno']);
 $heatno1 = pg_escape_string( $_POST['heatno1']);
 $pipeno2 = pg_escape_string( $_POST['pipeno2']);
 $heatno2 = pg_escape_string($_POST['heatno2']);
 $Djointno = pg_escape_string($_POST['Djointno']);
 $measuredlength = pg_escape_string($_POST['measuredlength']);
 $serialno = pg_escape_string($_POST['serialno']);
 $wthick= pg_escape_string($_POST['wthick']);
 $remarks= pg_escape_string($_POST['remarks']); 
 //<!-- #3 -->
$query = "Update fieldtally set  wthick = $wthick, pipeno=$pipeno,heatno1=$heatno1,pipeno2=$pipeno2,heatno2=$heatno2,Djointno=$Djointno,measuredlength=$measuredlength,serialno=$serialno,remarks=$remarks where pipeno = $pipeno;
          INSERT INTO fieldtally(wthick, pipeno,heatno1,pipeno2,heatno2,Djointno,measuredlength,serialno,remarks), 
                Select $wthick, $pipeno,$heatno1,$pipeno2,$heatno2,$Djointno,$measuredlength,$serialno,$remark,
                WHERE NOT EXISTS (select pipeno from fieldtally where pipeno = $pipeno)";

//<!-- #4a -->
 $result = pg_query($query);
 if (!$result) {
 $errormessage = pg_last_error();
 $message = "Error with query: " . $errormessage;
 }
 $message = sprintf ("These values were inserted into the pipeline database - %s %s %s %s %s %s %s %s %s",$wthick,$pipeno,$heatno1,$pipeno2,$heatno2,$Djointno,$measuredlength,$serialno,$remarks);
 }
 //<!-- #2 -->
 if(isset($_POST['submit_2'])){
 //Code to post fieldbend data under suto the database
 $pipeno = pg_escape_string( $_POST['pipeno']);
 $wthick1= pg_escape_string($_POST['wthick1']);
 $heatno1 = pg_escape_string( $_POST['heatno1']);
 $pipeno2 = pg_escape_string( $_POST['pipeno2']);
 $heatno2 = pg_escape_string($_POST['heatno2']);
 $Djointno = pg_escape_string($_POST['Djointno']);
 $measureddistance = pg_escape_string($_POST['measureddistance']);
 $benddegree = pg_escape_string($_POST['benddegree']);
 $bendtype= pg_escape_string($_POST['bendtype']); 
 $remarks= pg_escape_string($_POST['remarks']);
 //<!-- #3 -->
$query1 = "INSERT INTO fieldbend(pipeno,wthick1,heatno1,pipeno2,heatno2,Djointno,measureddistance,benddegree,bendtype,remarks)VALUES ('$pipeno','$wthick1','$heatno1','$pipeno2','$heatno2','$Djointno','$measureddistance','$benddegree','$bendtype','$remarks') ON DUPLICATE KEY UPDATE wthick1='$wthick1',heatno1='$heatno1',pipeno2='$pipeno2',heatno2='$heatno2',Djointno='$Djointno''";

//<!-- #4a -->
 $result1 = pg_query($query1);
 if (!$result1) {
 $errormessage = pg_last_error();
 $message1 = "Error with query: " . $errormessage;
 }
 $message1 = sprintf ("These values were inserted into the pipeline database - %s %s %s %s %s %s %s %s %s %s",$pipeno,$wthick1,$heatno1,$pipeno2,$heatno2,$Djointno,$measureddistance,$benddegree, $bendtype,$remarks);
 }
 //<!-- #2 -->
 if(isset($_POST['submit_3'])){
 //Code to post apptally data under suto the database
 $pipeno = pg_escape_string( $_POST['pipeno']);
 $wthick2= pg_escape_string($_POST['wthick2']);
 $tallytype = pg_escape_string( $_POST['tallytype']);
 $qty = pg_escape_string( $_POST['qty']);
 $serialno = pg_escape_string($_POST['serialno']);
 $referenceid = pg_escape_string($_POST['referenceid']);
 //<!-- #3 -->
$query2 = "INSERT INTO apptally(pipeno,wthick2,tallytype,qty,serialno,referenceid)VALUES ('$pipeno','$wthick2','$tallytype','$qty','$serialno','$referenceid') ON DUPLICATE KEY UPDATE wthick2='$wthick2', pipeno='$pipeno'";

//<!-- #4a -->
 $result2 = pg_query($query2);
 if (!$result2) {
 $errormessage = pg_last_error();
 $message2 = "Error with query: " . $errormessage;
 }
 $message2 = sprintf ("These values were inserted into the Pipeline database - %s %s %s %s %s %s",$pipeno,$wthick2,$tallytype,$qty, $serialno,$referenceid);
 }
 // Code to pull data from the database and load onto the form
 $query = 'select pipeno from fieldtally order by pipeno asc'; 
 $result = pg_query($db_handle,$query); 
 while ($row = pg_fetch_row($result))
 {
    // Creates Arrays to use in dropdowns
     $pipeno_array[] = $row[0];

 } 
 // This function creates dropdowns that will be used in the forms
 function dropdown($field_name, $num){
     // Creates the Dropdown
     //<!-- #5a -->
     $c = ($field_name == 'pipeno') ? ' onChange="check('.$num.');"' : '';
     echo "<select name=\"".$field_name."\" id=\"".$field_name.$num."\"$c>\n";
     echo "<option value=\"\"> --- Select --- </option>\n";
     // Chooses which array to use for Dropdown options
     global $pipeno_array;
     $name_array = ($field_name == 'pipeno') ? $pipeno_array : $wallthick;
     // Creates the Dropdown options based off the array above
     foreach($name_array as $k){
         echo "<option value=\"$k\">$k</option> \n"; }
     // Ends the Dropdown
     echo "</select>\n";
 }
?>
<html>
<head>
<meta charset="utf-8">
<title>UG Pipeline Field Data Capture</title>
</head>
<body>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     </head>
      <body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">

<!-- #5b -->
        function check(num){
           var pipeno_id = '#pipeno_'+num;
           var pipeno = $(pipeno_id).val();
           if(pipeno != ""){
             jQuery.ajax({
             type: "POST",
             url: "check.php" , 
             data:'pipeno='+pipeno,
             cache: false,
             success: function(response){
             var response_array = JSON.parse(response);
             $('#heatno1').val(response_array['heatno1']);
             $('#pipeno2').val(response_array['pipeno2']); 
             $('#heatno2').val(response_array['heatno2']);
             $('#Djointno').val(response_array['Djointno']);
             }           
            });
           }
           else{
           $('#heatno1').val('');
           $('#pipeno2').val('');
           $('#heatno2').val('');
           $('#Djointno').val('');}
            }
  </script>
          <!-- #4b -->
 <!--<?php printf($message);?>-->

 <!-- #6.1 -->
<form action="" method="post">
 <table width="800" cellpadding= "10" cellspacing="1" border="2">
 <tr align="center" valign="top">
 <td align="center" colspan="1" rowspan="1" bgcolor="#00CC00">
 <h3>Input Field Tally Information</h3>
      Select Wall Thickness:<select name="wthick" id="wthick">
 <!-- #7.1 -->
  <option value=""> --Select-- </option> 
  <option value="9.80">  9.80  </option>
  <option value="13.50"> 13.50 </option>
  <option value="15.90"> 15.90 </option>
  </Select>           
 Select Pipe No:<?php dropdown('pipeno', 1); ?> HeatNo1: <input type="text" name="heatno1" id="heatno1"><br /><br />  
 PipeNo2: <input type="text" name="pipeno2" id="pipeno2"> HeatNo2: <input type="text" name="heatno2" id="heatno2">Joint No: <input type="text" name="Djointno"><br /><br /> 
  Input measured Length: <input type="text" name="measuredlength"> Input Serial No: <input type="text" name="serialno"><br><br> Remarks: <input type="text" name="remarks"><br><br> 
 <!-- #8.1 -->
 <input type="Submit" name="submit_1" value="Submit">
 <!-- #9.1 -->
</td></tr></table></form>
<!-- #6.2 -->
 <form action="" method="post">
 <table width="800" cellpadding= "10" cellspacing="1" border="2">
 <tr align="center" valign="top">
 <td align="center" colspan="1" rowspan="1" bgcolor="#FF99FF">
 <h3>Input Field Bend Information</h3>
  Select Wall Thickness:<select name="wthick1" id="wthick1">
 <!-- #7.2 -->
     <option value=""> --Select-- </option> 
     <option value="9.80">  9.80  </option>
     <option value="13.50">13.50 </option>
     <option value="15.90"> 15.90 </option>
  </select>
 <!-- #10.1 -->           
 Select Pipe No:<?php dropdown('pipeno', 2); ?>   HeatNo1: <input type="text" name="heatno1" id="heatno1_2"> <br><br>
 PipeNo2: <input type="text" name="pipeno2" id="pipeno2_2"> HeatNo2: <input type="text" name="heatno2" id="heatno2_2"> Joint No: <input type="text" name="Djointno"> <br><br>
 Input Measured Distance: <input type="text" name="measureddistance"> Input Bend Angle: <input type="text" name="benddegree"> <br><br>
Select Bend Type:<select name="bendtype" id="bendtype">
    <option value=""> --Select-- </option> 
    <option value="Combo">Combo</option>
    <option value="SAG">SAG</option>
    <option value="OB">OB</option>
    <option value="SBRT">SBRT</option>
    <option value="SBLT">SBLT</option>
    <option value="HBLT">HBLT</option>
    <option value="HBRT">HBRT</option><p></p> 
  Remarks: <input type="text" name="remarks"><br></br>

  <input type="Submit" name="submit_2" value="Submit"> 
 <!-- #9.2 -->
</td></tr></table></form>
<!-- #6.3 -->

<form action="" method="post">
 <table width="800" cellpadding= "10" cellspacing="1" border="2">
 <tr align="center" valign="top">
 <td align="center" colspan="1" rowspan="1" bgcolor="#99FF33">
 <h3>Input App. Tally Information</h3>
 <!-- #11 -->
       Select Wall Thickness:<select name="wthick2" id="wthick2">
 <!-- #7.3 -->
     <option value=""> --Select-- </option> 
     <option value="9.80">  9.80  </option>
     <option value="13.50"> 13.50 </option>
     <option value="15.90"> 15.90 </option>
  </select>
 <!-- #10.2 -->             
 Select Pipe No:<?php dropdown('pipeno', 3); ?>  <br><br> Input Tally Type: <input type="text" name="tallytype">
 Input Tally Qty: <input type="text" name="qty"><br></br>  Input Serial No: <input type="text" name="serialno"> 
 RefID: <input type="text" name="referenceid"><br></br>
 <!-- #8.3 -->
 <input type="Submit" name="submit_3" value="Submit">
 </td></tr></table>
</form>

</body>
</html>

Php Script to load data onto the form field and push data back from the database - filename = check1.php

<?php
//Php Code to connect to postgresqldatabase
$PGHOST = "localhost:25376";
$PGDATABASE = "Pipeline";
$PGUSER = "postgres";
$PGPASSWORD = "Casa2009";
$PGPORT = 5432;
$db_handle = pg_connect("dbname=$PGDATABASE user=$PGUSER password=$PGPASSWORD");

// Code to pull data from the database and load onto the form  
$pipeno = pg_escape_string($_POST['pipeno']);
$query = "SELECT * FROM fieldtally1 WHERE pipeno = $pipeno ";
$result = pg_query($db_handle,$query); 
$row = pg_fetch_row($result);
$row_info = array('heatno1'=>$row[1],'pipeno2'=>$row[2],'heatno2'=>$row[3],'jointno'=>$row[4]);
$row_info = json_encode($row_info);
print_r($row_info); 
?>

the errors I get when I hit the submit button with or without data is this

Notice: Undefined variable: remark in C:\Users\iegbulefu\Documents\My Web Sites\Personal Site1\autopopulate.php on line 27

Warning: pg_query(): Query failed: ERROR: syntax error at or near "GGFF" LINE 1: ...no2=67677,Djointno=8,measuredlength=80,serialno=99GGFF,remar... ^ in C:\Users\iegbulefu\Documents\My Web Sites\Personal Site1\autopopulate.php on line 30

Shade
  • 31
  • 2
  • 10

2 Answers2

2

I would do this by using Ajax and JQuery. You would need to do 3 things - Add Ajax/JQuery code in head of document, create php file for Ajax to connect to, and add onChange, id & value attributes to fields.

In your <head></head> add this javascript after your <title></title>-

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function check(){   
    var pipeno = $('#pipeno').val();
    if(pipeno != "pipeno"){
      jQuery.ajax({
      type: "POST",
      url: "check.php",
      data: 'pipeno='+pipeno,
      cache: false,
      success: function(response){
     var response_array = JSON.parse(response);
     $('#wallthickness').val(response_array['wallthickness']);  
     $('#jointno').val(response_array['jointno']);
     $('#measuredlength').val(response_array['measuredlength']);
     $('#serialno').val(response_array['serialno']);}
    });
    }
    else{
         $('#wallthickness').val('');   
     $('#jointno').val('');
     $('#measuredlength').val('');
     $('#serialno').val('');}
    }
</script>

Then create a file named check.php with code -

<?php
 //Php Code to connect to postgresqldatabase
 include ("connection.php");
 // Code to pull data from the database and load onto the form  
 $pipeno = pg_escape_string($_POST['pipeno']);
 $query = "SELECT * FROM fieldtally WHERE pipeno = $pipeno ";
 $result = pg_query($db_handle,$query); 
 $row = pg_fetch_row($result))
 $row_info = array('wallthickness'=>$row[1],'jointno'=>$row[2],'measuredlength'=>$row[3],'serialno'=>$row[4]);

 $row_info = json_encode($row_info);
 print_r($row_info); 
?>

And finally, add id & value attributes to your form fields (Don't change your file, just update these lines)

Select Pipe No:<select name="pipeno" id="pipeno" onChange="check()"><option value="pipeno"> --Select-- </option> 
...  (keep your database connection / how you create your dropdown, etc here, just edit the option below)
 echo "<option value=\"$pipeno\"> $pipeno</option>";
... (keep your database connection / how you create your dropdown, etc. here)
</select> 
...
Input Joint No: <input type="text" name="jointno" id="jointno">
Input Wall Thickness: <input type="text" name="wallthickness" id="wallthickness">
Input measured Length: <input type="text" name="measuredlength" id="measuredlength">
Input Serial No: <input type="text" name="serialno" id="serialno">

UPDATED 10/19 Due to changed code -

I have put numbered anchors in your code, and the notes are at the end. You can do this all in 2 files, but the second file check1.php, can only have the 1 database query, or you will have errors in your ajax.

autopopulate.php-

<!-- #1 -->
<?php
//Php Code to connect to postgresqldatabase
$PGHOST = "localhost:25376";
$PGDATABASE = "Pipeline";
$PGUSER = "postgres";
$PGPASSWORD = "Casa2009";
$PGPORT = 5432;
$db_handle = pg_connect("dbname=$PGDATABASE user=$PGUSER password=$PGPASSWORD");

//<!-- #2 -->
 if(isset($_POST['submit_1'])){
 //Code to post data to the database
 $pipeno = pg_escape_string( $_POST['pipeno']);
 $wallthickness = pg_escape_string($_POST['wallthickness']);
 $heatno1 = pg_escape_string( $_POST['heatno1']);
 $pipeno2 = pg_escape_string( $_POST['pipeno2']);
 $heatno2 = pg_escape_string($_POST['heatno2']);
 $jointno = pg_escape_string($_POST['jointno']);
 $measuredlength = pg_escape_string($_POST['measuredlength']);
 $serialno = pg_escape_string($_POST['serialno']); 
 $wthick= pg_escape_string($_POST['wthick']);

//<!-- #3 -->
 $query = "INSERT INTO fieldtally1(pipeno,wallthickness,heatno1,pipeno2,heatno2,jointno,measuredlength,serialno,wthick)VALUES ('$pipeno','$wallthickness','$heatno1','$pipeno2','$heatno2','$jointno','$measuredlength','$serialno','$wthick') ON DUPLICATE KEY UPDATE wallthickness='$wallthickness',heatno1='$heatno1',pipeno2='$pipeno2',heatno2='$heatno2',jointno='$jointno',measuredlength='$measuredlength',serialno='$serialno',wthick='$wthick'";

//<!-- #4a -->
 $result = pg_query($query);
 if (!$result) {
 $errormessage = pg_last_error();
 $message = "Error with query: " . $errormessage;
 }
 $message = sprintf ("These values were inserted into the database - %s %s %s %s %s %s %s %s %s",$pipeno,$wallthickness,$heatno1,$pipeno2,$heatno2,$jointno,$measuredlength,$serialno,$wthick);
 }

 // Code to pull data from the database and load onto the form
 $query = 'select pipeno, wallthickness from fieldtally1 order by pipeno asc'; 
 $result = pg_query($db_handle,$query); 
 while ($row = pg_fetch_row($result))
 {
    // Creates Arrays to use in dropdowns
     $pipeno_array[] = $row[0];
     $wallthickness_array[] = $row[1];
 } 

  // This function creates dropdowns that can be used in your forms
 function dropdown($field_name, $num){
     // Creates the Dropdown
 //<!-- #5a -->
     $c = ($field_name == 'pipeno') ? ' onChange="check('.$num.');"' : '';
     echo "<select name=\"".$field_name."\" id=\"".$field_name.$num."\"$c>\n";
     echo "<option value=\"\"> --- Select --- </option>\n";
     // Chooses which array to use for Dropdown options
     global $pipeno_array, $wallthickness_array;
     $name_array = ($field_name == 'pipeno') ? $pipeno_array : $wallthickness_array;
     // Creates the Dropdown options based off the array above
     foreach($name_array as $k){
         echo "<option value=\"$k\">$k</option> \n"; }
     // Ends the Dropdown
     echo "</select>\n";
 }

 ?>
 <html>
     <head><title>UG Pipeline Field Data Capture</title></head>
      <body>
       <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
       <script type="text/javascript">
 <!-- #5b -->
        function check(num){
           var pipeno_id = '#pipeno_'+num;
           var pipeno = $(pipeno_id).val();
           if(pipeno != ""){
             jQuery.ajax({
             type: "POST",
             url: "check1.php",
             data: 'pipeno='+pipeno,
             cache: false,
             success: function(response){
             var response_array = JSON.parse(response);
             $('#heatno1').val(response_array['heatno1']);
             $('#pipeno2').val(response_array['pipeno2']); 
             $('#heatno2').val(response_array['heatno2']);
             $('#jointno').val(response_array['jointno']);
             //$('#measuredlength').val(response_array['measuredlength']); // this should be input from the user
            // $('#serialno').val(response_array['serialno']);  //This should also be input from the user
            }           
            });
           }
           else{
           $('#heatno1').val('');
           $('#pipeno2').val('');
           $('#heatno2').val('');
           $('#jointno').val('');}
            }
  </script> 

 <!-- #4b -->
 <?php printf($message);?>
 <!-- #6.1 -->
 <form action="" method="post">
 <table width="800" cellpadding= "10" cellspacing="1" border="2">
 <tr align="center" valign="top">
 <td align="center" colspan="1" rowspan="1" bgcolor="#64b1ff">
 <h3>Input Field Tally Information</h3>
      Select Pipe Thickness:<select name="wthick" id="wthick">
 <!-- #7.1 -->
  <option value=""> --Select-- </option> 
  <option value="9.8">  9.8  </option>
  <option value="13.5"> 13.5 </option>
  <option value="15.9"> 15.9 </option>
  </Select>           
 Select Pipe No:<?php dropdown('pipeno', 1); ?>  Select Wall Thickness:<?php dropdown('wallthickness', 1); ?><br /><br /> 
 HeatNo1: <input type="text" name="heatno2" id="heatno1"> PipeNo2: <input type="text" name="pipeno2" id="pipeno1"> HeatNo2: <input type="text" name="heatno2" id="heatno2"><br /><br /> 
 Joint No: <input type="text" name="jointno"> Input measured Length: <input type="text" name="measuredlength"> Input Serial No: <input type="text" name="serialno"><br><br> 
 <!-- #8.1 -->
 <input type="Submit" name="submit_1" value="Submit">
 <!-- #9.1 -->
 </td></tr></table></form>
 <p></p>

 <!-- #6.2 -->
 <form action="" method="post">
 <table width="800" cellpadding= "10" cellspacing="1" border="2">
 <tr align="center" valign="top">
 <td align="center" colspan="1" rowspan="1" bgcolor="#ff9d9d">
 <h3>Input Field Bend Information</h3>
  Select Wall Thickness:<select name="wallthickness" id="wallthickness">
 <!-- #7.2 -->
     <option value=""> --Select-- </option> 
     <option value="9.8">  9.8  </option>
     <option value="13.5">13.5 </option>
     <option value="15.9"> 15.9 </option>
  </select>
 <!-- #10.1 -->           
 Select Pipe No:<?php dropdown('pipeno', 2); ?>  Select Wall Thickness:<?php dropdown('wallthickness', 2); ?><br /><br /> 
 HeatNo1: <input type="text" name="heatno1" id="heatno1_2"> PipeNo2: <input type="text" name="pipeno2" id="pipeno2_2"> HeatNo2: <input type="text" name="heatno2" id="heatno2_2"><br /><br /> 
 Joint No: <input type="text" name="jointno"> Input Measured Distance: <input type="text" name="measureddistance"><br><br> 
 Input Bend Angle: <input type="text" name="benddegree"> Input Bend Type: <input type="text" name="bendtype"><br><br>
 <!-- #8.2 -->
 <input type="Submit" name="submit_2" value="Submit">
 <!-- #9.2 -->
 </td></tr></table></form>
 <p></p>

 <!-- #6.3 -->
 <form action="" method="post">
 <table width="800" cellpadding= "10" cellspacing="1" border="2">
 <tr align="center" valign="top">
 <td align="center" colspan="1" rowspan="1" bgcolor="#66CC66">
 <h3>Input App. Tally Information</h3>
 <!-- #11 -->
      Select Wall Thickness:<select name="wallthickness1" id="wallthickness1">
 <!-- #7.3 -->
     <option value=""> --Select-- </option> 
     <option value="9.8">  9.8  </option>
     <option value="13.5"> 13.5 </option>
     <option value="15.9"> 15.9 </option>
  </select>
 <!-- #10.2 -->             
 Select Pipe No:<?php dropdown('pipeno', 3); ?>  Select Wall Thickness:<?php dropdown('wallthickness', 3); ?><br /><br />            
 Input Tally Type: <input type="text" name="type">   Input Serial No: <input type="text" name="serialno"><br><br>
 Input Reference ID: <input type="text" name="referenceid"><br><br>
 <!-- #8.3 -->
 <input type="Submit" name="submit_3" value="Submit">
 </td></tr></table>
 </form>
 </body>
 </html>

check1.php-

<?php
//Php Code to connect to postgresqldatabase
$PGHOST = "localhost:25376";
$PGDATABASE = "Pipeline";
$PGUSER = "postgres";
$PGPASSWORD = "Casa2009";
$PGPORT = 5432;
$db_handle = pg_connect("dbname=$PGDATABASE user=$PGUSER password=$PGPASSWORD");

// Code to pull data from the database and load onto the form  
$pipeno = pg_escape_string($_POST['pipeno']);
$query = "SELECT * FROM fieldtally1 WHERE pipeno = $pipeno ";
$result = pg_query($db_handle,$query); 
$row = pg_fetch_row($result);
$row_info = array('heatno1'=>$row[1],'pipeno2'=>$row[2],'heatno2'=>$row[3],'jointno'=>$row[4]);
$row_info = json_encode($row_info);
print_r($row_info); 
?>

Here are the issues-

1 - Move all <?php ?> scripts to the top of the page. This will: (1) clean up your code, (2) be able to process all database queries at the same time.

2 - Your query to update fieldtally1 is now done before you get your dropdowns from the database.

3 - To fix your second issue after entering data into the input fields and click submit. it creates a new record in the database instead of populating the required columns in the database use INSERT INTO ... VALUES ... ON DUPLICATE KEY UPDATE .... If pipeno is already in the database (since it is a Primary Key) it will UPDATE instead of INSERT.

4 - I recommend saving your error or success message (#4a) and echo it at the top of your html (#4b).

5a - You changed from a hard coded pipeno dropdown, back to the dynamically dropdown using the function. So you are missing the javascript - onChange=check(); 5b - now that you are creating your pipeno & onChange=check(); dynamically, you have to change your check() function to get the id dynamically as well.

6 - $PHP_SELF is not valid. I think you were trying for $_SERVER['PHP_SELF'], but this is easily hacked, so it is better just to use action="". [6.1,6.2,6.3]

7 - When doing your <select><option> you were using the same value="", but each one needs to be different for you to get the value when posting. Also, most </option>'s were misspelled as </optio>. [7.1,7.2,7.3]

8 - If you have 3 forms on the same page, each one has to have a different name, or you will not be able to tell which submit button was clicked. [8.1,8.2,8.3]

9 - Your first two forms were missing closing tags - </td></tr></table></form>. [9.1, 9.2]

10 - In you 2 & 3 forms, you are using id's that are used in the 1st form. This is invalid as every id must be unique. [10.1,10.2]

11 - 3rd form uses id="wallthickness" that was used in form 2. see above about id uniqueness.

Sean
  • 12,379
  • 3
  • 26
  • 44
  • Thanks Sean for helping,I did the modifications, the script is able to create the form with the dropdown but it is not able to populate the dropdownlist or the listed formfeilds. It looks to me like the php script is not been accessed by the Javascript because It does not echo the cheque "connection succeded" to confirm connection to the database. I have modified my script above to refelct what I have so far. – Shade Oct 18 '12 at 15:21
  • Hi Sean, I have been working on the script, You recall, initially I had the Wallthickness to be a dropdown but the current script kind of made it auto populate instead of dropdown. Though both the autopopulate and the dropdown is currently not populating, I am just making the Wallthickness to be static populated as defined in the option and it is working perfectly fine, but the dropdown populate for the pipeno as well as the autopopulate defined for the various field is yet to function well. I have pasted the script above. I appreciate your help please! – Shade Oct 18 '12 at 17:07
  • It is not creating you `pipeno` dropdown, because you removed your database query. I did not want to retype your database query so that is why I just typed `...` before and after the `echo "";` to show that you just needed to update a few things with `id`, `value`, and `onChange`. You need to re-add your method of creating your dropdown. Also, you need to remove `if($db_handle){echo'Connection attempt succeeded.';}else{echo 'Connection attempt failed.';}` from your `check.php` file as this will cause issues with the Ajax post. – Sean Oct 18 '12 at 17:12
  • I also made some modifications on the PHP script which I posted also above now. – Shade Oct 18 '12 at 17:26
  • Ok! Reading your message now, let mje go through the script and modify as instructed here and run. Thanks – Shade Oct 18 '12 at 17:28
  • ookkk! Sean! Using your instrctions above, I got the two dynamic dropdowns for pipeno and wallthickness working and dynamically populating from the database also the static dropdown wall thickness is ok too. Now the issue is that the script is not populating the autopopulation field on the form. It appears to me that the script is not executing this line - url: "check1.php" which is where i believe the auto population function is located for the formfields. Please I have updated the script above to reflect what I have now. including the php script. Thank you very much for your time. – Shade Oct 18 '12 at 20:01
  • It appears the php script for the autopopulation 'check1.php' appears to be having issues with this lines - $row_info = array('wallthickness'=>$row[1],'jointno'=>$row[2],'measuredlength'=>$row[3],'serialno'=>$row[4]); because when I tried to past it into the body of the main script, it keeps giving me error at that line. this is what its says "Parse error: syntax error, unexpected '$row_info' (T_VARIABLE) in C:\Users\iegbulefu\Documents\My Web Sites\Personal Site1\autopopulate.php on line 82" $row_info = json_encode($row_info); print_r($row_info); – Shade Oct 18 '12 at 20:33
  • A couple of quick thoughts. In the javascript, you have commented out a `}`when you did - `//$('#serialno').val(response_array['serialno']);} `, you need to move it to the next line, or it will cause issues. In `check1.php`, it is not `$row_info = ...` that is the issue, it is the line before is missing the closing `;` - `$row = pg_fetch_row($result)`. Also, is all that code in `check1.php`? If so, that will cause issues with your Ajax post back to the page. `check1.php` should only have the code I posted. And in your new code, you have 2 dropdowns with `id="wallthickness`. I post more soon. – Sean Oct 19 '12 at 00:54
  • Hi Sean, thanks once again! I have made the necessary corrections and some other adjustments too sucht as reflecting only the fileds that are to be auto populated on the $row_info as well as including the field wthick to capture the static dropdown wallthickness items. I have posted the modified scripts above. I am still not able to get the autopopulation to run.Though the check1.php script appears to run ok when i run it by itself but the javascript is not pulling or posting information to it. Isaved the javescript as autopulate.php, is it right? – Shade Oct 19 '12 at 14:41
  • I made the php to be exactly what you have posted but it is still not populating the fields. Im just wondering what could be the issue here! I have a feeling its a minor isssue gere but unfortunatly i cantfind what it is.Thanks for all your help! i really do appraciate it. – Shade Oct 19 '12 at 19:45
  • It's not populating, because you first posted a hard coded `pipeno` dropdown, so I showed you how to include the `onChange="check();"`, but then you changed back to the dynamic function to create the dropdown, but did not add in the `onChange`. Also, you have numerous errors and invalid markup. What software are you using? As soon as I copied your code into Dreamweaver, and viewed in Firefox using Firebug, all these errors/issues were visible. I have posted a revised code with a lot of notes. I know that this works as I have a sample version here - [demo version](http://udeo.org/testphp5.php). – Sean Oct 20 '12 at 05:06
  • Hi Sean, After I made all the necessary corrections on the script, I am still not able to get the autopopulation to function. I downloaded and installed a trail version of dream weaver (this is my first time of using it), It tells me that "Dynamically related files cannot be discovered because there is no site definition for the document, it appears it needs me to set up a hosting server. I dont know how to ask it to use the Lmhost. Please I have posted the code above for your preview. Thanks for helping me. – Shade Oct 23 '12 at 15:25
  • On the code I eliminated the wallthickness dropdown listing leaving only the static dropdown and the pipeno dropdown listing. When IO run the script on my IIS, I didnt get any error its just that the autopopulation fields are not populating and when i tried to feed it manually, it gives me error stating something about the autopopulation. – Shade Oct 23 '12 at 15:35
  • I see that you updated `autopopulate.php` but did you also remove the extra code / update `check1.php`? If you have more than the db connection and the `// Code to pull data from the database and load onto the form`, it will cause the ajax to fail. – Sean Oct 23 '12 at 15:53
  • Hi Sean! I have taking all day to work on the script , I also tried to use the dreamweaver to search for errors though without much results from there. AFter making the necessary correction, I keep getting one particular error besides the fact that the autopopulation fields are not coming up but these are the 3 errors i get when i hit the submit buttons 1,2,3. im not sure if it from the inability of the autopopulate fields function because the errors are just the same. I have posted the modified script and the errors above. the check.php remains the same. thanks for helping me please – Shade Oct 23 '12 at 22:52
  • The script also complained about this line -, so i commented it out, this is the error it give on it (Notice: Undefined variable: message in C:\Users\iegbulefu\Documents\My Web Sites\Personal Site1\functionalbasisscripts\autopop.php on line 142) – Shade Oct 23 '12 at 23:10
  • Issue 1 - pg_query() error message. Apparently I was wrong. `INSERT INTO fieldtally1(...)VALUES (...) ON DUPLICATE KEY UPDATE ...` is only valid for MySQL, not Postgresql. See - [.../questions/1009584/how-to-emulate-insert-ignore-and-on-duplicate-key-update-sql-merge-with-po](http://stackoverflow.com/questions/1009584/how-to-emulate-insert-ignore-and-on-duplicate-key-update-sql-merge-with-po) & [.../questions/1109061/insert-on-duplicate-update-postgresql](http://stackoverflow.com/questions/1109061/insert-on-duplicate-update-postgresql) – Sean Oct 24 '12 at 08:09
  • Issue 2 - Undefined variable: message. `$message` is only being set if you click on one of you form submit buttons. Add the following line of code somewhere near the top - `$message = '';`. This way `$message` is defined, and then reset if `pg_query()` is successful. – Sean Oct 24 '12 at 08:13
  • Issue 3 - Not autopopulating. I noticed that I changed `check1.php`, back to `check.php` in the javascript function. Make sure it matches the file name. Also, are there `pipeno`s already in your Postgresql database. If not the dropdown won't populate, and when you change the select it will have nothing to change in the other fields. Do you have this live somewhere public that I can take a look at, or is it currently only on your computer? – Sean Oct 24 '12 at 08:18
  • Hi Sean, I have been struggling with the update code in postgresql becuase you were right in the point you made that postgresql handles the update code very differently. I found a sample of how to do it on the postgresqll documentation but it appears im not coding it rightly in my script as it works when i run it directly in my database. I will post my script so far in a short time. The autoppulate fields are still not functioning yet except the drop down – Shade Oct 26 '12 at 16:29
  • Helloo Sean, I have not made much progress in this script so far. I have succeeded in eliminating most of the errors but still my auto popluation fields are not populating every other thing seems to be working fine . I got something on Updating tables in postgresql and i have tried it out here though its not functioning perfectly, it appears to be hooked with the autopopulation fields area. please look at my updated script above and see if you can help. Thanks for all the efforts. Im highly encouraged by you. – Shade Oct 26 '12 at 18:43
  • Hi Sean, I will be at work tomorrow - Saturday to continue work on this, Im hoping I will be able to meet you online so that i can find ways to get you to see my database as i dont have it anywhere public for you to view. It is currently on my computer – Shade Oct 26 '12 at 19:51
0

If the data you want to populate the text field(s) is an attribute of your select option, I'd use jquery. Pull the selected options attributes you want to use, you can then output that to your text box with jquery also. It can be triggered by the change event on the select menue. For example..

$('#selectid').change(function() {
    var opt = $('#selectid option:selected');
    $('#text1id').val(opt.attr('attrfortext1'));
    $('#text2id').val(opt.attr('attrfortext2'));
    $('#text3id').val(opt.attr('attrfortext3'));
});

I'd argue to use Ajax to access another PHP file to parse your database and return a json encoded array with the data you want to populate the text fields with. Depending on how much data your sifting through, your method could ugly quickly if there were several attributes per option with 100's of options.

Craig

CraigH
  • 13
  • 3
  • Thanks Craig for your contribution, but unfortunately Im not very knowledgedable with jquery though i know its a concised Javascript code and I have used Javascript a little in my past scripting experience. Im going to give it a trial and hope it will do the job, but I still believe i will need the php to pull the data from the server and im just wondering in my head how to marry the two codes to get the function to work. – Shade Oct 17 '12 at 14:40
  • I have tired this but bits simply not making any headway for me – Shade Oct 17 '12 at 16:55