R
E
S
O
U
R
C
E
S
       Home      Products & Services      Contact Us      Links


WebHatchers will design & develop your site for you.
_______________________

Website Menu Heaven: menus, buttons, etc.
_______________________

Send us your questions.
_______________________

site search by freefind
_______________________

HOME
SEO, Google, Privacy
   and Anonymity
Browser Insanity
JavaScript
Popups and Tooltips
Free Website Search
HTML Form Creator
Animation
Buttons and Menus
Counters
Captchas
Image Uploading
CSS and HTML
PHP
AJAX
XPATH
Website Poll
IM and Texting
Databases—MySQL
   or Not MySQL
Personal Status Boards
Content Management
   Systems
Article Content
   Management Systems
Website Directory
   CMS Systems
Photo Gallery CMS
Forum CMS
Blog CMS
Customer Records
   Management CMS
Address Book CMS
Private Messaging CMS
Chat Room CMS
JavaScript Charts
   and Graphs




Free Personal Status Boards (PSB™)

Free Standard Free PSB

Free PSB Pro Version

Free Social PSB

Free Social PSB Plus (with Email)

Free Business PSB

Free Business PSB Plus (with Email)

PSB demo

Social PSB demo

Business PSB demo

So what's all this PSB stuff about?

Chart comparing business status boards

PSB hosting diagram

PSB Licence Agreement



Copyright © 2002 -
MCS Investments, Inc. sitemap

PSBs, social networking, social evolution, microcommunities, personal status boards
PSBs, social networking, business personal status boards
website design, ecommerce solutions
website menus, buttons, image rotators
Ez-Architect, home design software
the magic carpet and the cement wall, children's adventure book
the squirrel valley railroad, model railroad videos, model train dvds
the deep rock railroad, model railroad videos, model train dvds

Enter Record in HTML Form Creator Form

This script is called enter-record-in-html-form-creator-form.php

The Enter Record in HTML Form Creator Form script is one of a group of PHP scripts that handle both the administrative and end-user aspects of a general purpose HTML Form Creator that allows not just input boxes but multiple selection enabled select/option lists as well. In addition to the expectable editing scripts for both administrative and end-user functions, there's also a Search and Match script so that users can use the scripts to find other users with various individual or group commonalities, including proximity searches, i.e., find all the users within various distances. There are even private messaging scripts.

First, we start up a session and include the config.php script to ensure that our connection to our database is made correctly. This file has the codes below in it:

$theemailaddress = "yoursite@yoursite.com"; //EDIT ME
$roothostname = "localhost";
$theusername = "yourusername"; //EDIT ME
$thepassword = "yourpassword"; //EDIT ME
$thedatabasename = "yourdb"; //EDIT ME
mysql_connect("".$roothostname."","".$theusername."","".$thepassword."") or die(mysql_error());
mysql_select_db("".$thedatabasename."") or die(mysql_error());

We also use the checkid_.php script to ensure that the session id variable is set, and send the user to register-with-captcha_.php if it is not. Then we put the session variable 'username' into $U—we will be checking that it is set in a second. Then we define a named constant '_NODIRECTACCESS'. We include the config.php file (in the includes folder) which uses the PHP defined() function to check on this constant. If it is not set, we are thrown out of the config.php file like yesterday's trash.

Next we check if the session variables 'groupname', 'username', and 'userid' are set. If not, we are sent to the login script. We make sure $U is still equal to the session variable 'username', that it is not an empty string, and that it's at least 6 characters long or . . . you guessed it . . . the login script. We make sure the session id is set and send them away if not.

Next we do browser sniffing to deal with display quirks. Then we have several JavaScript calculation functions that are part of the algorithm for dealing with fixed positioning. Much as we'd like to claim credit for it, in truth it's actually JDenny who is the CSS and JavaScript genius who came up with this brilliant CSS and JavaScript fixed positioning code and put it on the Web to help those of us that were stumped trying to figure out good fixed positioning codes. Thanks a million JDenny! This has to be the most ingenious DHTML using CSS and JavaScript we've ever seen! (Note: The b.gif URL should be left as is, but you do NOT need a b.gif file: it is a dummy name just to keep the code working.) The CSS for BODY, the mytable id, and the menu id in the CSS styling section are part of this algorithm for fixed positioning as well. The BODY tag's CSS that uses t.gif for the background is using a real file. Make it yourself: it's simply an invisible 1-pixel gif, and this goes a long way to prevent any shimmering of the fixed-position side menu. If you are feeling lazy type in http://www.css-resources.com/t.gif and do Save As from the browser's File menu, since right clicking is dumb—right click WHAT?

In the JavaScript section, there is the check() function for validation of the user input. It runs off the onchange event which is echoed into place in the PHP function theoptions(). The check() function uses a regular expression pattern and the JavaScript search() method to check out one input box value at a time and an illegal value (or less than 1 or more than 50 characters) will cause an alert message outlining legal characters, after which the function will return false. This latter causes the cursor to stay on the current input box. The input box value, document.myform.elements[i2[h]].value, does not have a name like box1 or city, like one would expect, because the names of the input tags AND the select tags are all array values corresponding to field names in the MySQL database table whose name ends with _database. The PHP script reads these field names from the MySQL table with MySQL queries, then uses them in its PHP arrays as well as its JavaScript arrays.

We get the PHP data sent to JavaScript with the help of JavaScript Object Notation, also known as JSON, which has been part of PHP since PHP 5.2 arrived on the scene. There is no good way to get strings and arrays into JavaScript from PHP except JSON. Except for i2[h], the rest of document.myform.elements[i2[h]].value is simple dot notation of DOM (document object model) fame. Note that we stick the value found in document.myform.elements[i2[h]].value into the p[] array and return true if the value is okay, or if the value is an empty string we stick the value found into the p[] array and return false. This latter is to redo a p[] array value where the user changed his mind and decided to submit an empty value after all. (The p[] array gets filled with empty strings before the script has gone far. This is so empty values at the end of the p[] array will not result in "undefined" array elements that turn into NULL in MySQL. We prefer empty strings to NULL.) Also note that we change dangerous stuff into benign. We all know how dangerous the single quote is, so we turn all these into "·" which are middots. Better don·t than dont, right? If you have a better idea, insert that instead, or just leave it out of the allowed character list in the regular expression pattern. We also replace commas with "~", but then restore then to commas in the PHP script. We do this because the form sends its submitted values in a hidden field with a value that is a string that is a comma separated list of inputted values.

The donecheck() function is: function donecheck(){document.myform.f.value = p.toString();return true;}. But the initial donecheck() function was much more. However, it turned out that this initial function worked wonderfully in IE7, IE8, and IE9, but in NO OTHER BROWSER ON EARTH! So we ended up with just function donecheck(){document.myform.f.value = p.toString();return true;}. And we came up with other script adjustments to make up for the codes that were in the original function but are missing in the new—much shorter— function. Why the other browsers couldn't handle the code we cannot say. It's a mystery, discussed here—and the original function's code is supplied as well.

The donecheck() function is called by the onsubmit event, while onchange runs the check() function. Our original donecheck() function, discussed here, goes through and validates all input box entries, but no selected box entries, and for very important reasons. We expected that we'd be able to address the select box values selected, and we can IF WE ALLOW ONLY SINGLE SELECTIONS. But we are permitting multiple selections, and when we tried addressing the selected options we got only one.

There IS a way to get the other selected option values that involves:

for (var i=0; i < o1.length; i++) {
if (o1[i].selected){x=v.length;v[x]=o1[i].value;}}
if (v.length<1){v[0]=0;};z=v.toString();v=[];

This type of thing—above—gets the option values but not which were selected, for reasons unknown, for our current script, enter-record-in-html-form-creator-form.php—which is below. But the script above does get selected option values when used with an onclick event that runs a JavaScript function in which the parameters in the function call are used to send the data. I.e., ONCLICK="grabselected(this.form.Employment.options,this.form.males03.value . . . )" On a different, unrelated script of ours, there are many form inputs grabbed using this.form, in which the grabselected() function is run by an onclick event. Note that the grabselected function parameters at the bottom of the page in the previous link nearly fill the browser window all by themselves! To retrieve the values and send them to the PHP processing script, we use the JavaScript function grabselected(o1,o2,o3,o4 . . .) for the "this.form" input box DOM objects that end with ".value" (there are dozens) and for the select list DOM objects that end with ".options". These latter are then run through the above 3-line script to pull the multiple options values from them. It works flawlessly. But we did need 13 separate 3-line scripts like above to grab select list results from 13 different select boxes. There was likely a way to use one 3-line script and variables, but we were not having any luck with variable references in such scripts so we decided to rough it.

We cannot say why the script on this page (enter-record-in-html-form-creator-form.php) couldn't use this same idea—it simply did not work. Our guess is that as long as the data gets sent in simple dot notation DOM objects like this.form.Employment.options, which turn into simple array objects like o1[], all runs smoothly. But the minute you use fancy DOM objects like "document.myform.elements[i2[h]].value" which not only use variables but array variables as well, the browsers find themselves unprepared and return only one selected value as though we had used the selectedIndex property, which sets or returns the index of the selected option in a dropdown list. But we did not—we used the selected property. Which should have worked but didn't. Nice try, guys.

So, to make a long story short, we came up with a workaround. We let the $i2[$h] values be the name attributes to deal with the input boxes but used $i2[$h][] name attributes values for getting the options of the select boxes. These were array values turned into arrays, technically. They started out as MySQL data which we processed into a PHP array before using JavaScript Object Notation, also known as JSON to pull it into a JavaScript array. We used echo "<select multiple='multiple' name='".$i2[$h]."[]'>"; for echoing select box tags (in PHP) and echo "<input type='text' name='".$i2[$h]."' maxlength='".$s[$h]."' size='".$s[$h]."' value='' onchange='return check(".$h.");'>"; for input box tags. This works fine in all browsers. Don't get confused that we are talking about a multi-dimensional array $i2[$h][]. We are not. The $i2[$h] part turns into a field name such as "field1". So name='".$i2[$h]."[]' would then be name='field1[]' to the browser.

Why couldn't we use straight HTML? Because we were writing a general purpose form creator where values, names, etc. were all unknowns and we allowed mixing an unknown quantity of select tags and input tags in a form of unknown length and whose parts were stored in a MySQL database table. Arrays full of values to use as name attributes were essential, both as PHP arrays and JavaScript arrays. So you can see why the simple no-array-values method of getting the selected options was a nonstarter. And we couldn't use the "this.form" and grabselected() type of scenario outlined above, which could have worked except that would be an ungodly mixture of PHP and JavaScript in which we have to use variables for everything since we don't know how many tags of what type to put in the function calling parameters ahead of time, and in order to figure it out on the fly we'd have to use the tagName property which returns the tagname of an element as a string, and without which we'd be unable to know how to build each parameter, all of which we'd have to somehow string together separated by commas as we called the grabselected() function from an onclick event. All this would have to get echoed together by PHP all the while praying that the browsers wouldn't freak out. We played with this idea and ran into a comedy of syntax errors so we figure that strategy was worth about as much as an election-year promise.

What good did the '".$i2[$h]."[]' configurations do—the ones that were array values turned into arrays? Happily, the browsers allow us to stick [] after our select box name attributes (i.e., name='whatever[]') so there IS a way to get all our selected options once we get to our PHP script and start processing data. We process the data that is from select tags (not input tags) by doing:

$pos = strrpos($j[$h], "|");
if($pos>0){$ar=$_POST[$i2[$h]];$j[$h]=implode(",",$ar);}


What this does is find the values with | in them and replaces them with POSTed array values which it then implodes into strings for database storage. Let's go through this. In the JavaScript JSON-using code block near the end of the script, we have for (h = 0; h < num_rows; h++) {if(e[h]){p[h]="||";}}. The $e[] array in PHP is given ones for select and zeros for input in the function theoptions(). It decides this on the basis of looking into the table ending with "_options" and if it finds the field name it puts a 1 in $e[]—otherwise it leaves the originally initialized value of 0. If the options table has the field it means the administrator turned one of the form tag types from input to select by putting option values in the record that also has that field name. We use JavaScript Object Notation, also known as JSON to pull $e[] into a JavaScript array. The loop just mentioned sticks "||" into all p[] array element values that are parallel to e[] array element values that are 1 rather than 0.

The function theoptions() is our form display function that echoes select and option and input tags to the screen. So we see why finding a 1 in e[] gets us to put "||" into the p[] array. The p[] array gets stringified and dumped into a hidden form field by document.myform.f.value = p.toString(). The rest of the p[] array contains input values or other || flags signifying select/option tags. Since there was no way to get more than one selected value into the p[] array, it was only useful to indicate the presence of select/option tags, not send selected options. We used strrpos() instead of strpos() to find the last occurence of a string in another string, since the function returns the position of the string and position 0 would get confused with $pos being false. This is also why we used two | characters, so the last one found could never be at position 0. So when we find a | and $pos is greater than 0, we grab the POSTed array value as an array value's array, to implode into a string for db storage, since that will be the form we will need this data in when we use the data from the submitted form to display records or do matching searches.

The function checkdb() is to check the table name prefix (which will be followed by "_database") to make sure the user uses only allowed characters. In PHP, the MySQL command SHOW TABLES LIKE '$table' will check to see if the table exists and give the user a message and a chance to retry if it does not. The function fix() deals with quirks about how various browsers handle fixed positioning.

Next comes the CSS. We already looked at the weird stuff in BODY, the mytable id and the menu id styling. These too help browsers handle fixed positioning.

Check out the function theoptions(), in the PHP section. The function echoes one form input value for one tag name (whose name attribute is a table field name) which is either a select tag or an input tag. It displays it on the screen via the PHP echo function. It only does one because the function is used from a for loop that loops through all array values. The first thing is to check the options table for that field name. If it's found, the $e[] array gets a 1 to signify it is a select/option tag. But if the PHP function mysql_num_rows() finds no rows, an input tag is echoed, including the size attribute and maxlength attribute—which is the value the form creator entered as input size. The onchange event runs the check() function for on-the-fly input validation. But the user can skip some boxes or click elsewhere instead of using tab, so the original donecheck() function would sure have been nice for final validation and input filtering. However, there is a chance that, to the administrator who created the form, NOT doing this is preferrable, because allowing empty values is seen as positive. It would be easy to have the PHP validation script we are using give messages about empty field values, but we did not see the point. We just made sure either empty strings or acceptable, non-dangerous characters were in the fields.

If mysql_num_rows() finds one or more rows, the echoing of a select tag and option tags commences. The name attribute becomes the field name array element's array. No, we're not stuttering. All was explained above. Next, using the PHP functions mysql_fetch_array() to get the options from the query result and htmlentities() and stripslashes() for security, we explode the comma-separated string of option values from the table and with a loop we echo them to the screen as selectable select list options. Note that we wedged a "No preferences" option in there first and marked it selected. This is so those without preferences about various form items will be able to ignore such items and the script will still perform well, indicating his lack of a preference.

The function underscore() takes the table of form questions and processes them into values that can and will be used as MySQL table field names, allowing only alphanumerics and underscores in the new array $i2[]. The middot (what JavaScript converted all single quotes to) characters which are sent from the table turn into space middot space, so to get them turned into _ characters so they can be field names requires the str_replace() function to replace "_middot_" since the spaces on the sides of the word middot were already converted to _ by the previous preg_replace() function. So what is the $i[] array? It is from the table and it contains the raw question data like "How many men, in your group, make over $50,000 a year (!) and a % goes to charity?" Allowed are ' ! ? $ % ( ) _ - , . and letters and numbers, even though the ' will get converted to middot. But the $i2[] array will contain only "How_many_men__in_your_group__make_over__50_000_a_year_____and_a___
goes_to_charity_", which is okay as a field name, a tag's name attribute, a JavaScript array element value, or a PHP array element value.

We've already started a session at the start of the whole script. Now let's use it. It turns out that session variables are a much easier way to deal with values that need to survive refresh/restart and submissions than sticking hidden fields, POSTs, and GETs everywhere full of flags or values. The first thing the user does on this record entry page is to enter the table prefix name for this form and it is POSTed to $d. If the POST has reasonable content, it will (if found in the MySQL db as part of a table name) be used as the table prefix (since the prefix will be used before _database, _options, and _input tables in relating to MySQL tables). The db query SHOW TABLES LIKE '$aa' will be used to check whether the table prefix exists and therefore the tables exist. The $_SESSION['db']=$db command establishes a session variable, but if the mysql_num_rows() function finds no rows in the result set, this is quickly unset and the user sees "Table does not exist. Try again."

The very next command is that session variable being checked, and if the result is finding out it is unset, the echoed table prefix entry form will be presented again. Users cannot get anywhere until a valid name is entered. The input is filtered in the JavaScript checkdb() function. Bad input gets an alert and a refocusing of the cursor in the input box. Good input lets the user into the rest of the script, as you can see by the next PHP "if" conditional.

We GET a variable 'more' from the query string when the form gets submitted, and this puts a "y" into the variable $more—but only if submitting happened. We stick the user's id into $id. Then we see if this user already has a record in the database table $aa. If so, his member id will be in the member_id field of the table. If this id IS found, and the form has NOT just been submitted, the user sees "You already have a record. Continue or Cancel? To Continue, click OK. To Cancel, click Cancel." This is displayed, not in a JavaScript alert, but in a confirm box, that has hard-wired buttons OK and Cancel. If they click on the Cancel button, it means they changed their minds and they get sent back to the profile-and-account-management.php script they just came from. If they click OK, the script continues. Notice that if their member id IS found, and the form HAS just been submitted, the user's database table record is deleted with the use of the DELETE FROM statement.

Next, we define some arrays and table name suffixes. Then we do a query to grab all the items and inputsizes from the db table $db."_inputs" and we stick the former in the $i[] array and the latter in the $s[] array, using a php while() statement and array_push() function. Now the underscore() function is run. Then the $e[] array is initialized with all zeros via use of the array_fill() function. In the parameters, the first number is what element to start on, the next value is the number of elements to define in the array, and the final value is what to stuff into these elements. The $p[] array gets filled with empty strings, and this will, like $e[], get turned into a JavaScript array for use in JavaScript functions.

If data is entered and the form survives the JavaScript validation scripts, the hidden field with the name "entered" will have a 1 and the hidden field named "f" will have the comma-separated string containing the stringified contents of the p[] array where input box values and select box || flags were stashed. The PHP
explode() function is used to explode the string back into an array, $j, which now has what the p[] array had in it. The str_replace() function turns the ~ characters back into commas, now that they no longer can interfere with the string that had comma-separated values. Next we do a for loop wherein we use the PHP strrpos() function to detect select options (since the $e[] array lost its flags during the submit operation). This gets us POSTing in the $i2[$h] array containing all selected options for that select box. (The $i2[] array is NOT the array with these options. The $i2[][] array is, yet we're not saying dimensions. We are saying the value of $i2[$h]—let's say rumpsize—is an array name—let's say rumpsize[]. THIS, then, is the array with the select/option tag's selected options.) We implode them into a comma-separated string for storage in a MySQL database table field for later display or matching search use. If there are no | characters, it is an input box value, so it gets a substr() function run on it that limits its length to whatever the original form creator stipulated.

Then a regular expression pattern is used that limits its characters to acceptable ones only, using the PHP preg_replace() function. This is run on any select box values too, but since these were entered in the first place by the form creator, this is more of a hollow gesture than a precaution. We also knock out Ctrl characters like NULL, which is \x00. The security needs of our script, like most scripts, dictate that we use the mysql_real_escape_string() function on this content before it goes into the field named $i2[$h] in the MySQL db table as the value in $k. The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the previous INSERT operation. As you can see, the $w flag starts out at 0 but once the first field in the record has data INSERTed into it, the $w variable increments so the rest of the fields' new values will go into the record using the same id but using the UPDATE statement. Note that the member_id is entered as well, using the $_SESSION['userid'], which the login script created from the user's my_members table id. The page returns to profile-and-account-management.php after this record entry.

Next we create the overall display page, and in a for loop we call the theoptions() function repeatedly until all the form's input tags and select tags are displayed. The hidden "f" field and "entered" field are echoed. Note the ?more=y URL query string on the action script (itself) and the onsubmit='return donecheck()' that sticks all form input into a comma-separated string with the || flags for select/option-related data.

Next, we get the PHP data sent to JavaScript with the help of JavaScript Object Notation, also known as JSON. We will be needing the i2[] array, the e[] array, the s[] array, and the num_rows variable, so we get those now. We already discussed how we put "||" values in the p[] array where a parallel e[] array has a 1—this is so we have a flag to tell the PHP script which inputs are from input boxes and which are from select/option lists. Recall that PHP is a server language so its values are in place, so therefore this JavaScript block, coming after the PHP block, will find its PHP values as needed. Finally, we display the DIV called menu which merely has data input directions and a link back to the profile-and-account-management.php script from whence the user got to this script.

The script below is called: enter-record-in-html-form-creator-form.php

<?php
session_start();
include_once"checkid_.php";
$U=$_SESSION['username'];
define('_NODIRECTACCESS', TRUE);
include_once"includes/config.php";
if (!isset($_SESSION['groupname']) || !isset($_SESSION['userid']) || !isset($_SESSION['username']) || $_SESSION
['username']<>$U || !isset($U) || $U=="" || strlen($U)<6 || !isset($_SESSION['sessionid'])){echo '<script language="javascript">alert("Please login."); window.location = "login_.php";</script>';}
?>

<html>
<head>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>Enter Record in HTML Form Creator Form</TITLE>
<meta name="description" content="Enter Record in HTML Form Creator Form">
<meta name="keywords" content="Enter Record in HTML Form Creator Form,Form Creator record,add record,php,javascript, dhtml, DHTML">
<script language="javascript">
mactest=(navigator.userAgent.indexOf("Mac")!=-1) //My browser sniffers
is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1
Netscape=(navigator.appName.indexOf("Netscape") != -1)
msafari=(navigator.userAgent.indexOf("Safari")!= -1)
wsafari=0; if(!mactest&&msafari){wsafari=1;msafari=0}
is_opera = 0; if(window.opera){is_opera=1}
is_ie_mac = 0; is_ie=0;if(document.all){is_ie=1}
if(is_ie&&mactest){is_ie_mac=1}

var i2=new Array();var p=new Array();var s=new Array();var e=new Array();

function calculateBgX(oElement) {return document.body.scrollLeft - getOffsetLeft(oElement);}

function calculateBgY(oElement) {return document.body.scrollTop - getOffsetTop(oElement);}

function getOffsetTop(oElement) {var iResult= oElement.offsetTop;
while (oElement.offsetParent) {oElement = oElement.offsetParent;iResult += oElement.offsetTop;}
return iResult;}

function getOffsetLeft(oElement) {var iResult= oElement.offsetLeft;
while (oElement.offsetParent) {oElement = oElement.offsetParent;iResult += oElement.offsetLeft;}
return iResult;}

function check(h){
var ck_item = /^[A-Za-z0-9 \!\$\%\-\_\(\)\?\.\,\']{1,50}$/;
var l=document.myform.elements[i2[h]].value;
if (l.search(ck_item)==-1)
{alert("Please enter 1 to "+s[h]+" letters, numbers, period,\ncomma, space and these for item: ' ! ? $ % ( ) _ -"); if(l==""){p[h]=l;};return false;}
document.myform.elements[i2[h]].value=l.replace(/'/gi, "·"); l=document.myform.elements[i2[h]].value; document.myform.elements[i2[h]].value=l.replace(/,/gi, "~"); l=document.myform.elements[i2[h]].value; p[h]=l;return true;}

function donecheck(){document.myform.f.value = p.toString();return true;}

function checkdb(){
var ck_item3 = /^[A-Za-z0-9_]{3,20}$/;
if (document.nameform.db.value.search(ck_item3)==-1)
{alert("Please enter 3 to 20 letters, numbers, or underscore."); document.nameform.db.focus();return false;}}

function fix(){if(Netscape||is_opera){e=document.getElementById("mytable");e.style.position="absolute";e.style.marginTop=0+"px";
e=document.getElementById("j");e.style.top=p+"px";}}

</script>
<STYLE TYPE="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;text-align:left;background-image:url(t.gif);background-attachment:fixed;background-color:#ccc;}
p, li, td {font:13px Verdana; color:black;text-align:left}
h1 {font:bold 28px Verdana; color:black;text-align:center}
h2 {font:bold 24px Verdana;text-align:center}
h3 {font:bold 15px Verdana;}
#mytable {margin:26px 0 0 150px;width:820px;padding:10px;border:2px solid blue;background: url('b.gif');background-attachment: fixed;background-position: expression((calculateBgX(this))+"px "+(calculateBgY(this))+"px");background-color:#eee;}
#table1 {width:100%;border:1px solid blue;text-align:center}
#menu {background-color:#eee;position:fixed;left:2px;width:130px;padding:5px;border:2px solid blue;position: expression("absolute");top: expression(eval(document.body.scrollTop)+60);}
#getdbname {position:absolute;top:104px;left:353px;}
</STYLE>
</head>
<body onload="fix()">

<?php

function theoptions(){
global $i,$i2,$s,$e,$h,$aaa;
$sql = mysql_query("SELECT options FROM $aaa WHERE field_name='$i2[$h]'") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows==0){
echo "<tr><td width='470' align='left'><span style='color:red'>*</span>".$i[$h];
echo "</td><td width='330' align='left'>";
echo "<input type='text' name='".$i2[$h]."' maxlength='".$s[$h]."' size='".$s[$h]."' value='' onchange='return check(".$h.");'></td></tr>";
}else{
$e[$h]=1;
echo "<tr><td width='470' align='left'><span style='color:red'>*</span>".$i[$h];
echo "</td><td width='330' align='left'>";
echo "<select multiple='multiple' name='".$i2[$h]."[]'>";
$row = mysql_fetch_array($sql);
$j=explode(",",htmlentities(stripslashes($row[0]), ENT_QUOTES));
echo "<option selected value='No preference'>No preference</option>";
for ($d=0;$d<count($j);$d++){
echo "<option value='".$j[$d]."'>".$j[$d]."</option>";}
echo "</select></td></tr>";}}

function underscore(){
global $i,$i2;
$replacement="_";
$pattern9 = '/[^A-Za-z0-9_]/i';
for ($h = 0; $h < count($i); $h++) {
$i2[$h]=preg_replace($pattern9, $replacement, $i[$h]);$i2[$h]=str_replace("_middot_","_",$i2[$h]);}}

$d=mysql_real_escape_string($_POST['db']);if(strlen($d)>2){
$db=$d;$aa=$db."_database";$exists = mysql_query("SHOW TABLES LIKE '$aa'") or die(mysql_error());
$_SESSION['db']=$db;$num_rows = mysql_num_rows($exists);
if($num_rows==0){unset($_SESSION['db']);unset($db);unset($d);mysql_close();
echo '<script language="javascript">alert("Table does not exist. Try again");</script>';}}

if(!isset($_SESSION['db'])){
echo "<div id='getdbname'><form name='nameform' id='nameform' method='post' action='enter-record-in-html-form-creator-form.php' onsubmit='return checkdb()'>db name&nbsp;<input type='text' id='db' name='db' maxlength='20' size='20'><input type='submit' value='submit'></form></div>";}

if(isset($_SESSION['db'])){$more=$_GET['more'];
$db=$_SESSION['db'];$aa=$db."_database";$memid=$_SESSION['userid'];
$sql=mysql_query("SELECT * FROM $aa WHERE member_id='$memid'");
$num_rows_found = mysql_num_rows($sql);
if($num_rows_found>0 && $more<>"y"){echo '<script language="javascript">var answer = confirm ("You already have a record. Continue or Cancel? To Continue (and replace your current record), click OK. To Cancel, click Cancel.");if (!answer){window.location = "profile-and-account-management.php";} </script>';}

if($num_rows_found>0 && $more=="y"){$sql=mysql_query("DELETE FROM $aa WHERE member_id='$memid'");}

$s=array();$i=array();$i2=array();$j=array();$e=array();
$a=$db."_inputs";
$aa=$db."_database";$aaa=$db."_options";

$sql=mysql_query("SELECT item,inputsize FROM $a ORDER BY N");
$num_rows = mysql_num_rows($sql);
while($row = mysql_fetch_array($sql)){
array_push ($i, htmlentities(stripslashes($row['item']), ENT_QUOTES)); array_push ($s, htmlentities(stripslashes($row['inputsize']), ENT_QUOTES));}
underscore();
$e=array_fill(0,$num_rows,0);$p=array_fill(0,$num_rows,"");

if($_POST['entered']=='1'){
$f=$_POST['f'];$w=0;
$j=explode(",",$f);
$j=str_replace("~",",",$j);
for ($h=0;$h<count($j);$h++){
$pos = strrpos($j[$h], "|");
if($pos>0){$ar=$_POST[$i2[$h]];$j[$h]=implode(",",$ar);}
else{$j[$h] = substr($j[$h],0,$s[$h]);}
$pattern="/[^A-Za-z0-9 !$%-_()\\?\\.\\,\\·]/i";
$j[$h]=preg_replace($pattern, "", $j[$h]);
$j[$h]=preg_replace('/[\x00-\x1F\x7F]/', '', $j[$h]);
$k=mysql_real_escape_string($j[$h]);
$member_id=$_SESSION['userid'];
if ($w==0){mysql_query("INSERT INTO $aa (member_id,$i2[$h]) VALUES ('$member_id','$k')");$id=mysql_insert_id();
$w++;
}else{
mysql_query("UPDATE $aa SET $i2[$h]='$k' WHERE id='$id'");}}
echo '<script language="javascript">window.location="profile-and-account-management.php";
</script>';}

echo "<center><h1>Enter Record in HTML Form Creator Form</h1></center>";
echo "<div id='mytable'><a name='form1'></a>";
echo "<form name='myform' id='myform' method='post' action='enter-record-in-html-form-creator-form.php?more=y' onsubmit='return donecheck()'>";
echo "<table id='table1' border='1' width='800' style='table-layout:fixed'><col width='470'><col width='330'>";
echo "<tr><th width='470' align='center'>Questions <span style='color:red;font-size:13px'>(* = required)</span></th><th width='330' align='center'>Answers</th></tr>";
for ($h = 0; $h < $num_rows; $h++) {theoptions();}
echo "<input type='hidden' name='entered' value='1'><input type='hidden' name='f' value=''>";
echo "</table><center><BR><input type='submit' value='submit'></center></form></div>";
mysql_close();
unset($b);unset($f);unset($w);
}
?>

<script language="javascript">
var num_rows = <?php echo json_encode($num_rows); ?>;
var i2 = <?php echo json_encode($i2); ?>;
var s = <?php echo json_encode($s); ?>;
var p = <?php echo json_encode($p); ?>;
var e = <?php echo json_encode($e); ?>;
for (h = 0; h < num_rows; h++) {if(e[h]){p[h]="||";}}
</script>

<div id='menu'>
<b><a HREF="profile-and-account-management.php">GO BACK</a><BR><BR>For record entries, enter one or more letters, numbers, period, comma, space and these as entries:<BR>' ! ? $ % ( ) _ -<BR>Hold down Ctrl key to select multiple options.</b><BR><BR><hr><BR>( ' will change to · )
</div>
</body>
</html>

The "All-browsers-but-IE-Bug" Mystery

The essence of the bug is this. Only IE could recognize arrays and array values in the function below. The other browsers choked on this, hopping out of the function faster than a guy leaving an elevator full of farting children once the door opens. The onsubmit event in the form that called the function got them to the function, below, but in checking with temporary alert boxes, only simple variables were recognized. Values like i2[h] and the dot notation element accessing statement that used these array values were NOT recognized. This function was used—initially—as the onsubmit-run input validation script for the data input form. It would return false after an alert if users put in bad data or no data. All inputs were completed when this function was run by form submission.

But here's where it REALLY gets weird. The check() function, near the beginning of the above script, used document.myform.elements[i2[h]].value and in this function ALL browsers easily could recognize arrays and array values! The check() function is run by the onchange event and all text input boxes used it for on-the-fly validation. The reason for the donecheck() function, originally, was both input validation and loading of the p[] array with values, which gets stringified into one long string and stuck into a hidden form field which gets POSTed to the PHP script during submission. IE loved all this. Others did not. We did not use proprietary IE functions or statements, nor do some bizarre, esoteric coding. So why did we have to switch strategies once we had perfectly-working, good code in IE and we began testing the other browsers (Opera, Windows Safari, Chrome, and Firefox)? And how could other browsers recognize arrays in one function but not another? Moving things around so that various code blocks were in different orders did not work—only IE worked. The others kept screwing up and sending an empty p[] array to the PHP script, resulting in a MySQL table record full of NULL values.

The toString() method converts an array to a string and returns the result, and all browsers support this. Our use of elements[i2[h]] is supported in JavaScript, or so it says in the Javascript Best Practices. So why did our onchange event running a function with such array values encounter cross-browser support, but our onsubmit event running a function with such array values encounter only IE support? A few places on the Net, if one searches in Google, describe screw-ups after onsubmit that occur in Firefox but not IE, but the bug described here was not seen elsewhere. At least, we couldn't find it. If anyone has any ideas about how to solve this riddle, wrapped in a mystery, inside an enigma, shrouded in bizarreness, please let us know! Perhaps someone sees the light where we see only haze, in the problem of the "All-browsers-but-IE-Bug" Mystery.

function donecheck(){
var ck_item2 = /^[A-Za-z0-9 \!\$\%\-\_\(\)\?\.\,\']{1,50}$/;
for (h = 0; h < num_rows; h++) {
if(e[h] != 1){
if (document.myform.elements[i2[h]].value.search(ck_item2)==-1)
{alert("Please enter 1 to "+s[h]+" letters, numbers, period,\ncomma, space and these for item: ' ! ? $ % ( ) _ -"); document.myform.elements[i2[h]].focus();return false;}}}
for (h = 0; h < num_rows; h++) {
if(e[h] != 1){
l=document.myform.elements[i2[h]].value; document.myform.elements[i2[h]].value=l.replace(/'/gi, "·"); l=document.myform.elements[i2[h]].value; document.myform.elements[i2[h]].value=l.replace(/,/gi, "~");}
if(e[h]==1){var z="|"+h+"|";}
if(e[h] != 1){p[h]=document.myform.elements[i2[h]].value;}else{p[h]=z;}}
document.myform.f.value = p.toString();return true;}