Solved

Multiple javascript forms array passed to PHP

Posted on 2004-10-05
24
693 Views
Last Modified: 2010-08-05
I have a large set of form questions (350) that are divided into 8 forms that are displayed sequentially on one large document (over 32 screens).   Yes, I know it would be "easier" to make this one form.  That is not the question or the issue.

The results of each the 8 forms are stored in a showformTotal array (8 elements) that I want to process via PHP at the completion of the 8 forms.  So the 9th form becomes a superform.   Why mix them?   Because PHP does allow for multiple loops as Javascript does.  8 questions per page.  7 pages per form.   8 forms per document + a superform.

The problem I am having, as others before, is how to pass the simple JS showformTotal array to a php results page and to the mySQL database at the same time.   That is the essential, but daunting, question.

I can either write (insert or update) the results to a mySQL table, reference the current row number and pass an ID variable to the results page for a "lookup."   Or I can pass the showformTotal array from the forms document to the results page.   It is the specific coding of a showPHPtotal PHP-based array variables that is confusing.

I am getting stuck passing the javascript-based showformTotal array to a showPHPtotal PHP-based array.

Help greatly appreciated.
0
Comment
Question by:bodywise
  • 11
  • 11
  • 2
24 Comments
 
LVL 4

Expert Comment

by:Georgiana Gligor
ID: 12235119
I'm proposing an alternate solution, if it doesn't fit don't blame me, I'm just trying to think as if I were "in your shoes" :-)

One idea: make a temporary table (let's say it's called [TEMP]) to hold intermediate forms data (the 8 ones); when a "subform" is submitted, you add data to the temp table, and reference this data by the session ID.

when it comes to process it all, take out of [TEMP] all data with the respective session ID, process the data, and then remove it from the [TEMP] table; or leave it there if you need reporting like "how many people have not finished all 8 forms", etc. It'll grow large this table, so it's recommended to wipe it from time to time, so that data access is faster.

if you have user accounts, then don't use session ID as a reference in the [TEMP] table, use the userID instead

Cheers,
     Georgiana
0
 
LVL 27

Accepted Solution

by:
Diablo84 earned 500 total points
ID: 12236079
ok, if i follow the question the only way to pass data between client side JS and server side PHP so basically your options there are either the query string or a post form, preferably the latter bearing in mind this is a large array.

So i would put the array into a hidden field in a form using javascript*, and then either have the user submit it manually or use a simple piece of js in the body onload tag to submit it automatically when the page loads (eg.<body onload="document.forms.form_name.submit();"> ) depending on exactly how you have worked your system.

*This is the tricky part, i can't help you much here as im not much of a JS guy but you need to get the JS array data into a useful format that we can easily read using PHP. If the array indexes are numeric based then its going to be a much easier task, if its an associative array then not so straight forward. I am going to work with this in hope that the indexes are not important, so ideally you need to write the JS array into the hidden field in this format item1|item2|item3 etc (seperating each item by a |), should be able to do this with a loop to output each array item value i would imagine but im not a JS guy as i said so cant say for sure.

From the PHP perspective you can then do this on the processing page (ie. that defined in the form that contains the hidden fileds action):

<?php

$arr = $_POST['name_of_hidden_field']; //you now the string sent from client side on the server
$arr_items = explode("|",$arr); //you now have your string back in array form with numeric indexes

//you could then loop through each item

foreach ($arr_items as $var) {

//run your query for each or whatever you need to do
//the variable $var will contain the value for the array
//item on each loop

}

?>
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12236095
Note: This isn't a typical method of doing such things quite simply because its inconvienient and not particularily efficent however as you have said you have your reasons for doing this.

A simpler approach may be using PHP sessions, or more specifically a session array then at each phase of the form assign the newly posted values to the session array which will be globally available around your pages without the need for a client side array.

eg.

<?php
session_start(); //initialize or continue the session - at TOP of page!

$_SESSION['arr'][] = $_POST['input_name']; //example of adding post value to the session array

//at anytime you can see the contents of the session array using
echo "<pre>";
print_r($_SESSION['arr']);
echo "</pre>";
?>
0
 

Author Comment

by:bodywise
ID: 12238003
Wow.  thank you for such a thoughful set of responses.

Logically, this split into 8 forms because the questionnaire is so long that it has 8 secitons each with a separate scorie.  From a systems perweptive, it makes much more esnse to keep these as 8 forms.  I know this inot the usual programming convetnion, but that is the confining switaituoin.  it is why I come to such edperts for additiona crative soltions.  problem sovling is good.

here is the site to show you how long and what is the flow of the program.  JS allows mutliple loops and quick recall until the gfinal processing is done.  that is also logical, although,not the docnvetion.

http://www.antiagingnow.com/secure/reg_forms/array_test.php

using a temproary teable is good suggetsion, but I have spoent so much time creating a JS holding array that works.   I aprpeaite the suggestion.

using a session variable is closer, since it invloives parallel JS and PHP holding arrays.

Diablo84 is much closer with the suggestion of the $_POST in put.
BTW what is the diffence betwee using


<form action="whatever.php" method="post" name="frmFoo">
  <script language="javascript">
    echo "<input type='hidden' name='getAct' value='" + getAct.join(",") + "'>\n";
    echo "<input type='hidden' name='getTries' value='" + getTries.join(",") + "'>\n";
    echo "<input type='hidden' name='getScore' value='" + getScore.join(",") + "'>\n";
  </script>
  <input type="submit" name="cmdSubmit" value="Send POST">
</form>
0
 

Author Comment

by:bodywise
ID: 12238141
(sorrry for the previous set of typos):

Wow.  Thank you for such a thoughtful set of responses.

Logically, this is split into 8 forms because the questionnaire is so long, that it has 8 sections each with a separate score.  From a systems perceptive, it makes much more sense to keep these as 8 forms.  I know this not the usual programming convention, but that is the confining situation.  It is why I come to such experts for additional creative solutions.  Problem solving is good.

Here is the site to show you how long and what is the flow of the program.  JS allows multiple loops and quick recall until the final processing is done.  That is also logical, although, not the convention.

http://www.antiagingnow.com/secure/reg_forms/array_test.php

Using a temporary table is good suggestion, but I have spent so much time creating a JS holding array that works.   I appreciate the suggestion.

Using a session variable is closer, since it involves parallel JS and PHP holding arrays.

Diablo84 is much closer with the suggestion of the $_POST input.
BTW what is the difference between using $HTTP_POST_VARS[] and $_POST[]?

*Please let me work on this and I will be back later tonight.*

from a separate discussion this was offered, although the coding is wrong.

<form action="whatever.php" method="post" name="frmFoo">
  <script language="javascript">
    echo "<input type='hidden' name='getAct' value='" + getAct.join(",") + "'>\n";
    echo "<input type='hidden' name='getTries' value='" + getTries.join(",") + "'>\n";
    echo "<input type='hidden' name='getScore' value='" + getScore.join(",") + "'>\n";
  </script>
  <input type="submit" name="cmdSubmit" value="Send POST">

The getAct is very similar to my JS based showformTotal[]  array.
 
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12238335
I just had a look at the link you posted and while the JS makes less sense to me then would be convienient here it seems that the whole form (including the multiple pages) is handled within one file without making multiple requests to the server. I suppose that would make sense as there wouldn't be any other way to maintain the JS array without server side support any other way.

Anyway, this is good in one sense because i believe its a more straight forward situation, and at this point in time i don't think there is a need for the php session array - that would have been useful it multiple page calls were being made but shouldnt be needed here.

So, definitely focus on the POST option, join the javascript array together using a common character | or , etc in a hidden field then this can be posted to the server side, "explode"d and then processed.

>> BTW what is the difference between using $HTTP_POST_VARS[] and $_POST[]?

As such nothing, $HTTP_POST_VARS is the old way or writing $_POST (which is now the preferred method). At this point in time both work to the same effect however i expect one day they they will deprecate the old method.

Incidently, the code sample you posted looks to be along the right lines, im not sure exactly whats wrong with it but i would guess it could be an incorrect method of integrating the JS with php, i think you would need document.write instead of the php echo.

The important part is

getAct.join(",")

because that joins the array together in a string seperated by commas which can then be posted. php wise you could then handle it like this:

<?php
$arr = $_POST['getAct'];
$arr_items = explode(",",$arr);
?>

so $arr_items would contain your reconstructed array on the server side.

Anyway good luck with it, if you run into any problems we can dig a little deeper and see where we end up.

|)iablo

0
 
LVL 4

Expert Comment

by:Georgiana Gligor
ID: 12238533
well, it seems like Diablo was faster than me on this one.

just a note: JS is something that I avoid, so always trying to get simpler and more efficient directly in PHP

i'll leave you with Diablo, i have to go home soon :-)

Georgiana
0
 

Author Comment

by:bodywise
ID: 12240209
Georgiana,

There is always the balance between presenting too much information and too little.   I appreciate your suggestions, but JS does make more sense in this case.  I have found that the mix of JS on the client side is best for rapid recall of information and less servers calls and handles all calculations.  The PHP then stores all database results and response pages.  Also, ideally this is really a loop in a loop in a loop.  *PHP can't do that.*   Right now there are two loops per form.   This is actually one one very long "page" with 8 forms.   It has to do with the "visibility" function.

To Diablo84,

Thanks for your continued input.  We are getting closer and we are down to the critical variable pass.

<?php
$arr = $_POST['getAct'];
$arr_items = explode(",",$arr);
?>

Will this php script pass the JavaScript variable?  That is the paramount question.   I thought you needed to enclose this all in a <script language=Javascript></script> which is where I keep getting hung up.   JS doesn't like embedded PHP scripts.  It all just stops.

On the previous example which is in a <script>:
<script language="javascript">
echo "<input type='hidden' name='getAct' value='" + getAct.join(",") + "'>\n";

is wrong.  It should be:

document.write(  '<input type="hidden" name=' + getAct + ' value='" + getAct.join(",") + "'>\n ' );
You have to do a little two step to get the JS variable passed to the input statement.

Then I will pose one more critical thought later ....

greatly appreciated.






0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12240377
Lets flow through the theory...

You have a form at the end of your Javascript checkboxes which will contain one (or more - depending on if you have the information stored in just one JS array or several)  hidden fields.

Within this hidden field you will have a value which is basically the JS array joined together with a specific character in a string, the name of this input would be "getAct". This of course relates to this line you have shown:
document.write(  '<input type="hidden" name=' + getAct + ' value='" + getAct.join(",") + "'>\n ' );

The form would then be submitted and its data posted to a php script (so its action should point to the name of your script - eg. <form name="form1" action="yourscript.php" etc).

In this PHP script at the moment you would have the two lines that have come up before:

<?php
$arr = $_POST['getAct'];
$arr_items = explode(",",$arr);
?>

Now basically when you send a form to a php page the contents of the form fields are stored in an associative super global array which is called $_POST. So if you have an input field called "getAct" you can access the contents of this field using $_POST['getAct'] which is what has been done above.

This means that the php variable $arr contains the string that was derived from the JS array in the hidden field.

The next line contines to split the string up back into an array using the , character as the break so $arr_items should be your new server side array.

For testing purposes you can use the following to check that everything has worked correctly, it will give you a "human friendly" representation of the array:

<?php
echo "<pre>";
print_r($arr_items);
echo "</pre>";
?>
0
 

Author Comment

by:bodywise
ID: 12245802
Diablo,

I'm back.  I have been studying your comments diligently for the last few hours.  I understand the general flow, but can't make this work.  Alllow me to quote two rather lengthy parts of code that are generated by DMX that I have then modifed according to our discussion.  See if you can find the problem, although I still think it is in this assignment statement:

$showPHPtotal = $_POST['showformTotal'];    // similar to your $arr = $_POST['getAct'];

here is the php scripting:

$editFormAction = $_SERVER['PHP_SELF'];

$showPHPtotal = $_POST['showformTotal'];    // as you suggested
$showPHPtotal_items = explode(",",$showPHPtotal);   // as you suggested

if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . $_SERVER['QUERY_STRING'];   // I think this only for a get statement not post
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "results_form")) {
  $insertSQL = sprintf("INSERT INTO edge_answers (dopamine, choline, gaba, serotonin, dopamine_def, choline_def, gaba_def, serotonin_def) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", $showPHPtotal_items);

  mysql_select_db($database_xxxxxxx, $connxxxxxx);
  $Result1 = mysql_query($insertSQL, $connxxxxxx) or die(mysql_error());

  $insertGoTo = "array_test_results.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }   // I think this is superfluous
  header(sprintf("Location: %s", $insertGoTo));

then here is the super-form hidden input statement:

<form action="<?php echo $editFormAction; ?>" method="POST" name="results_form" >
<script language="JavaScript" type="text/JavaScript">
document.write( '<input name="showformTotal" type="hidden" value="' + showformTotal + '" >');    //most important
formpage = 0;
pagenum = 'page' + j;
      document.write( '<div id=' + pagenum + ' class="page">' );
      document.write( '<H4>Brain Neurotransmitter Survey<\/H4>');
      document.write( '<p class="category">Results and Intrepretation of all questiuons<\/p>' );
      document.write( '<p class="checkoff">(click to tabulate final answers<\/p>');
      goforward = '<input type="submit" id="C8" value="Submit to see all scores" >';
      document.write('<p>', goforward, '<\/p>');
      document.write( '<p class="pagenums">' + 'page number ' +  formpage + '<\/p>');
      document.write('<\/div>');
</script>
<input type="hidden" name="MM_insert" value="results_form">
</form>

Really close -- but not there.    Again, I am trying to write the final array to the database and then pass the parameters to the result page for display.

Mucho appreciated ...

0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12247268
ok before i look at the code in too greater detail there could be any number of issues with this one so let me got over the most obvious ones first then il look at the code.

1) Is the form on the same page as your other JS code? I was thinking along the lines of putting it at the end of the checkbox questions which is what i hope you have done.

If the form is on another page then the JS array will be lost because its maintained client side and will not be maintained between pages.

2) The forms action is $_SERVER['PHP_SELF'], if you didnt know that means that its basically going to post the data to itself. This leads to the question is the PHP code on the same page as the form?

If not then you need to change the forms action, it may actually be easier in this case to process the script on a seperate page.

Il take a look at your code now.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12247398
Ok, taken a look and heres my thoughts


1) With the above in mind also your form line may as well just be

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" name="results_form" >

Instead of:

<form action="<?php echo $editFormAction; ?>" method="POST" name="results_form" >

To cut out the need for the "middle man" variable.

That said, again if the processing script is on another page then just enter the name of that page instead of <?php echo $_SERVER['PHP_SELF']; ?>


2) This is where things could get complicated for simple reasons.

There seemed to be a lot of unnecessary code in that script so at this point i have stripped it back to just what you need (as far as i can see). Theres a couple of issues here so !read below! the code - the code WILL NOT be functional at this point - i need more information.

<?php
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "results_form")) {

$showPHPtotal = $_POST['showformTotal'];    // as you suggested
$showPHPtotal_items = explode(",",$showPHPtotal);   // as you suggested

//you didnt have a connect statement in your code, not sure if
//you have it elsewhere but i included it here just incase
$connxxxxxx = mysql_connect("host","username","password") or die(mysql_error());
mysql_select_db($database_xxxxxxx, $connxxxxxx) or die(mysql_error());

//SEE NOTE!! regarding the query
$insertSQL = sprintf("INSERT INTO edge_answers (dopamine, choline, gaba, serotonin, dopamine_def, choline_def, gaba_def, serotonin_def) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", $showPHPtotal_items);

mysql_query($insertSQL) or die(mysql_error());

}
//you only need these two lines if you want to redirect to another page after the query is run
header("Location: array_test_results.php");
exit;
?>

Issue A) This is the lesser problem of the two, you mentioned passing the results to a final page to display them, i think using the query string for this is a little impractical so i would suggest running a fresh database query on the final page to pull out the last inserted row would make more sense. We can come to this later.

Issue B) The way the query is set up at the moment is illogical, i can't make sense of what you are trying to do with it.

Basically at the point of the query all you have is an array of values which represent the choices made, however you are trying to insert multiple values into multiple fields, this just wont work.

When dealing with arrays you have to loop through each array item to be able to process the data OR insert the array into a string (or something similar) if its all to go in one row. At the moment this is not going to happen.

We need to step back for a second here and i need to understand clearly what you are trying to do so i propose this, if you could give me an example of what data you want inserted into each field we should be able to work towards a solution.

At the moment you have several fields in your table: dopamine, choline, gaba, serotonin, dopamine_def, choline_def, gaba_def and serotonin_def. I am presuming each field represents one section of the questionnaire however we just have one array containing ALL of the answers at the moment.

So if you can show me (an example) of what data would go into each field, eg.

dopamine - "sample data for this field exactly how it should look"
choline - "sample data for this field exactly how it should look"
gaba - "sample data for this field exactly how it should look"

and so on for each of the 8 fields.


0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:bodywise
ID: 12256385
Diablo,

I'm back again.  Close but then far.  I have been playing with this all day.  If I could award you 1000 points I would :)

I can force the form to enter data into the database and then call the response page.  But I can't seem to get any variables being passed, so the response page just defaults to the set value.  Here are the 3 areas where I am getting hung up:

I don't fully understand the explode function.  I changed the variable names slightly here:

from the php functions and variables at the top of the page:

$showPHPtotal_items = explode(",",$showPHPtotal);   // very clever and important step

1. Great function but how do I get this to display a series of number rather than a single string?  To wit ... I have "foced" a series numbers to make this work.  I don't understand how to make $showPHPtotal_items fill in these fictitious values 12,30,35,12,15,13,16,5.

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "results_form")) {
  $showPHPtotal = $_POST['showformTotals'];    // **still the most critical conversion step***
  $showPHPtotal_items = explode(",",$showPHPtotal);  // re format the array
  $insertSQL = sprintf("INSERT INTO edge_answers (dopamine, choline, gaba, serotonin, dopamine_def, choline_def, gaba_def, serotonin_def) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", 12,30,35,12,15,13,16,5 );    // push the array into the database.

You can see that I tried to insert  $showPHPtotal_items where the  12,30,35,12,15,13,16,5 are entered.  But $showPHPtotal_items is a string and not a formated series of numbers.

This originally was derived from another large function that converted strings.  Let me know if you want to see more of this.   A series of GetSQLValueString($HTTP_POST_VARS['showformTotals'], "int")  instead of  $showPHPtotal_items.  

2.  The form seems right:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" name="results_form" >
<script language="JavaScript1.2" type="text/JavaScript">
document.write( '<input name="showformTotals" type="hidden" value="' + showformTotal + '" >');
    .....
      goforward = '<input type="submit" id="C8" value="Submit to see all scores" >';
      document.write('<p>', goforward, '<\/p>');
</script>
<input type="hidden" name="MM_insert" value="results_form">
</form>

3.  The variable passed to the results page could either be 'showformTotals' with value showformTotal (an array)
or simply finding the current line record ID number and calling the entire results set from the database that has now been succesfully writen.  I have verified that the values are being inserted into the database but only by the above routine of simply entering test nubmers.

again to show you how this how this looks:

http://www.antiagingnow.com/secure/reg_forms/array_test.php

Your diligence and help is immensely appreciated ... I hope we can bring this to conclusion with a simple set of results that can be laeld --- answer.



0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12257422
1)

Ok first thing, it seems that we are actually doing more then is needed ironically, I thought your JS array was a more complex entity but i see what is happening now.

The purpose of explode is to basically break the string apart into an array again however, rather convieniently, you don't need to do this in this case because its already in a convienient form to feed straight into the query.

To fill you in on the theory side of things on the client side - when the array is handled by JS - its type is array, eg. array(2,8,1,4,5,"etc"). When you write the value into the hidden field ready to be sent server side using the JS join function this array was basically turned into a string type in the format of "2,8,1,4,5,etc". When dealing with just numbers and database queries you don't need to add single quotes around the values so there is no need to explode the string into an array and reformat it, we should be able to directly plug the post value into the database.

SO you could should work as this:

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "results_form")) {
  $showPHPtotal = $_POST['showformTotals'];
  $insertSQL = "INSERT INTO edge_answers (dopamine, choline, gaba, serotonin, dopamine_def, choline_def, gaba_def, serotonin_def) VALUES ($showPHPtotal)";
  $insertSQL = mysql_query($insertSQL) or die(mysql_error());
}

AS long as that post item is an 8 number sting seperated by comma's (eg. 2,3,5,2,8,5,3,2).


2) Ok next thing your form. Looks ok except i do not any longer see the presence of the join function to convert your JS array to a string to be put in the hidden input field, a critical step. I am going ot have to presume that you know what you are doing there but as i  said its very important for that array to be in a very specific format in that hidden field otherwise your query is going to error.

3) I am thinking that it wil be easiest to pass an ID and run a fresh query, we can address this one later, i'd like to get the above working correctly first.
0
 

Author Comment

by:bodywise
ID: 12259942
More lucid.  Simpler and elegant.  All the requirements I seek for any solution.

$insertSQL = "INSERT INTO edge_answers (dopamine, choline, gaba, serotonin, dopamine_def, choline_def, gaba_def, serotonin_def) VALUES ($showPHPtotal)";

Takes about 20 lines of complex, involuted  code and simplifies it into 2 lines of far more meaningful code.  :)

In the end, this one line is the final answer to the question of assigning a JS array to a PHP array.

 $showPHPtotal = $_POST['showformTotals'];

Let me work on this today and get back to you again tonight.    This has been a most highly valuable problem solving session.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12263114
Glad to be helping. Its nice to be dealing with a question which is different from the usual ones that get asked.

Let me know how you get on.
0
 

Author Comment

by:bodywise
ID: 12271654
Diablo,

Again thanks for your guidance.  I am really stuck.  This is one of those deceptively “simple” projects that have a complex array of sub-solutions.   I think 99% of all “forms” are the same repetitious sort of address files.   This being 350 questions, with subsection and scores and the interpretations at the end, has taken me a huge amount of time.   But it will apply to about 3 other important and long forms I need to complete.

Here is where I am stuck.  You may or may not be able or have the inclination to offer further solutions.  Any suggestions still remain highly valued.  You seem to be a real professional.  (So am I).   But my  questions cut across, Javascript, php, and even more specifically DMX derived php so I follow DMX (macromedia) conventions to generate some of the more arcane “housekeeping” code.  I may have to ask another forum participant about a few other statements.  Even this statement has to be correct:

$Result1 = mysql_query($insertSQL, $connxxxx) or die(mysql_error());   //critical statement that cannot be altered

And the query string that is generated still seems superfluous to me as you have mentioned.  I am not sure why it is being generated for a POST statement.

My task is to:

1. pass the array from the Javascript-based (and php enabled) form to the php results page or generate a way of indexing the correct record number (row number) to access the mysql database from the results page.

2. pass the javascript showformTotal array from Javascript to php.  I am fairly certain I am doing this but still have not been able to confirm this in any way.

3. So here is the most immediate question.  I cannot entirely follow the logical of this and then some lines are deeply buried in some include files.

4. Sequence the save to database and then follow up with a lookup for the current record or row number.

From the top of my php scripting you see a GetSQLValueString function.  It is not specifically set up to format arrays.   I can generate a series of 8 inputs to make these arrays but I think there is a much simpler way of doing this.   We have talked about this but none of the strings or lines you have provided, which seemed the most elegant – work.   Later I may even want to input all 350 questions into an array.  Input statements will be too much.  Saving to a php database first is the way to go.

<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
$editFormAction = $HTTP_SERVER_VARS['PHP_SELF'];

if (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
  $editFormAction .= "?" . $HTTP_SERVER_VARS['QUERY_STRING'];
}  // probably superfluous

if ((isset($HTTP_POST_VARS["MM_insert"])) && ($HTTP_POST_VARS["MM_insert"] == "results_form")) {
$insertSQL = sprintf("INSERT INTO edge_answers (PID, dopamine, choline, gaba, serotonin, dopamine_def, choline_def, gaba_def, serotonin_def) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",              
GetSQLValueString($HTTP_POST_VARS['showformTotal[0]’, "int"),
                       GetSQLValueString($HTTP_POST_VARS['showformTotal[1]'], "int"),
                       GetSQLValueString($HTTP_POST_VARS['showformTotal[2]'], "int"),
                       GetSQLValueString($HTTP_POST_VARS['showformTotal[3]'], "int"),
                       GetSQLValueString($HTTP_POST_VARS['showformTotal[4]'], "int"),
                       GetSQLValueString($HTTP_POST_VARS['showformTotal[5]'], "int"),
                       GetSQLValueString($HTTP_POST_VARS['showformTotal[6]'], "int"),
                       GetSQLValueString($HTTP_POST_VARS['showformTotal[7]'], "int"));   // I know these are inefficient and wrong

  mysql_select_db($database_connxxx, $connxxxx);

  $Result1 = mysql_query($insertSQL, $connKiowa) or die(mysql_error());  // highly important

  $insertGoTo = "array_test_results.php";
  if (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {     // not needed why generated
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $HTTP_SERVER_VARS['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

$numRow_rsEdge = "20";

if (isset($_POST['PID'])) {
  $numRow_rsEdge = (get_magic_quotes_gpc()) ? $_POST['PID'] : addslashes($_POST['PID']);
}  // also looks like a GET statement not a POST statement

mysql_select_db($database_connKiowa, $connKiowa);

$query_rsEdge = sprintf("SELECT * FROM edge_answers WHERE PID = '%s'", $numRow_rsEdge);
$rsEdge = mysql_query($query_rsEdge, $connKiowa) or die(mysql_error());
$row_rsEdge = mysql_fetch_assoc($rsEdge);
$totalRows_rsEdge = mysql_num_rows($rsEdge);
?>

again much appreciated
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12272336
Hi bodywise, I will come back to this tomorrow when i have time to give it undivided attention.
0
 

Author Comment

by:bodywise
ID: 12272368
Thanks.   Apreciated.
0
 

Author Comment

by:bodywise
ID: 12275548
Diablo,

I know that most exchanges are designed to be short becasuse of short attention span.  But really tight and useful answers seem to be few and far between.  I have tightened the code and my questions to this one aspect.  

- Passing javascript to php does require a form input -- but it can be done.  
- The cummulative holding array (scores) cannot be passed by input but must be split into its integer elements.  
- Multiple forms can be submitted from a single page when using this ingenious method of writing all screens (forms) to one page but making them "visible" one by one with special <div> statements.  This was obtained from:
http://www.devx.com/webdev/Article/10483/1954?pf=true

I now know that you cannot "input" an array.  I thought you could.  And maybe I am missing something.  But I had to split the array into its 8 elements and the php code now works fine.   But ...

What I have discovered is that the holding array of answers that gathers the scores from each of the 8 forms needs to be "updated" or "refreshed" on the final screen.  That is where I am currently stuck.  How to write the javascipt code that refreshes.  I know I am now very close.   This seems to be a concept that is logically very simple, but techincally far too difficult (because it is not the "convention").  In fact, it would seem that a method or could could be written to act as the holding array and then refreshed for the final screen.  Others have suggested using session arrays or even cookies, but my piont is to do all the housekeeping on the client side until the final submit -- after the 8 forms are completed.  I know there are many out there that are trying to solve this same problem in other guises.   This is a very common problem!

So here is the final super-form.  It can be further simplified, but I wrote the onChange statements here to show what I am tryign to do.  Maybe it's onClick.  Or maybe it is still onSubmit placed in the <form> line.  I can't figure this out.  But the flow here is much more evident.

It does write to the mysql database and call the response page.  But the value scores being written are all still 0 as they were initalized:

<form action="<?php echo $editFormAction; ?>" method="POST" name="results_form" >
<input name="showfinalTotal1" type="hidden" value=0 onChange="this.value = document.form1.total.value">
<input name="showfinalTotal2" type="hidden" value=0 onChange="this.value = document.form2.total.value">
<input name="showfinalTotal3" type="hidden" value=0 onChange="this.value = document.form3.total.value">
<input name="showfinalTotal4" type="hidden" value=0 onChange="this.value = document.form4.total.value">
<input name="showfinalTotal5" type="hidden" value=0 onChange="this.value = document.form5.total.value">
<input name="showfinalTotal6" type="hidden" value=0 onChange="this.value = document.form6.total.value">
<input name="showfinalTotal7" type="hidden" value=0 onChange="this.value = document.form7.total.value">
<input name="showfinalTotal8" type="hidden" value=0 onChange="this.value = document.form8.total.value">
<script language="JavaScript" type="text/JavaScript">
formpage = 0;
pagenum = 'page' + j;
      document.write( '<div id=' + pagenum + ' class="page">' );
      document.write( '<H4>Brain Neurotransmitter Survey<\/H4>');
      document.write( '<p class="category">Results and Intrepretation of all questiuons<\/p>' );
      document.write( '<p class="checkoff">(click to tabulate final answers<\/p>');
      document.write('<p>', goforward, '<\/p>');
      goforward = '<input type="submit" id="C8" value="Now submit to see all scores" >';
      document.write('<p>', goforward, '<\/p>');
      document.write( '<p class="pagenums">' + 'page number ' +  formpage + '<\/p>');
      document.write('<\/div>');
</script>
<input type="hidden" name="MM_insert" value="results_form">
</form>

I'm still not sure why DMX writes "query strings" in the php scripting part.  They do seem to be unnecessary in a "post" form.

And I am still a bit curious where the $Result1 = mysql_query($insertSQL, $connxxxx) or die(mysql_error());  is defined.

thanks again ...
0
 

Author Comment

by:bodywise
ID: 12288379
Diablo,

I awarded the points since you have been so very patient, diligent and helpful.  But I would like to re-open the last comment in a separate question.

con mucho gusto,
bodywise
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12289421
bodywise, apologies for not returning to this, i have recently been having a conflict of opinions with the CS admin about another question so have not been in a particularily good mood with EE at all lately and subsequently haven't been as willing to donate so much of my free time to their cause.

|)iablo
0
 

Author Comment

by:bodywise
ID: 12290826
Sorry to hear of the internal strife.  I will be discrete and say it is a loss to others.   I have found your thinking to be clear, logical, thoughtful and not glib or tangential.   I am much closer to the answer I seek and have learned a huge amount along the way of the internal scripting developed by DMX.  But javascript remains an exceptionally powerful language.   I still feel that good design uses both, much as I have suggested.   Write if there other places to find you.

with regards,
bodywise
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12291537
Thank you for the kind words bodywise, it is much appreciated. I don't particularly want to leave this site on the basis of principle as i genuinely enjoy sharing my knowledge but at this point in time i am in a state of two minds about it.

With regards to JavaScript, it has always struck me as a very interesting language however, as i have said my knowledge of it is very minimal. This is mainly because of the fact that i am yet to find an online resource that has enough information to cover all of the fundamentals of the language.

When i started learning PHP and became involved with the server side aspect of the web, i gradually lost interest in the client side technologies that i started out with, JS became one of those things that i touched on but never took hold of with both hands.

My opinion now is a combination of a client side and server side technology working in harmony has great potential to produce very good results, something i will hopefully find the time to experiment with one day.

Anyway, as i am currently unsure of my status on this site i will be contactable at the address in my profile. If you need any information related to PHP you can contact me there. I cannot guarantee an instant response and perhaps not as much of an in-depth solution as i would usually provide here but i will do what i can if needed, it depends on my status at the time. There are however several other good PHP programmers active on this site who will be able to help for more immediate solutions.

Best Wishes.



0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now