Jump to content

problems with inserting / updating arrays in mysql


endswithaW

Recommended Posts

You know, the PHP file is pretty complicated, and I'm having trouble cutting it apart to give you the basics.  So, I'll try to explain how it works, give you the JavaScript and a minimal PHP framework, and let you work on the PHP yourself.  If you still need help, let me know.

 

In your PHP file, load all possible options into an array, $all_options.  If the user has pre-existing choices, load them into an array called $user_options.  (I had used the numerical value of the ENUM in the database as the key and the string value as the value.  Using the number instead of the whole string saves alot of output if you have a long, wordy list.)

 

When you render the initial SELECT MULTIPLE in PHP, for each value, check if it's in the user's preselected options (use in_array), and if it is, also print SELECTED for that OPTION.  After the form is completely rendered, the following JavaScript block moves those selected OPTIONs into the second SELECT MULTIPLE and also saves those values in the JavaScript array "originalSelection" (for resetting).  The onSubmit selects all values in the second SELECT MULTIPLE as only SELECTED OPTIONs get passed to your submission script.  The JavaScript function getInsertionIndex() sorts the placement of a moved OPTION.

 

As far as writing to your database table, just delete a preexisting value(s) on an update, and write a new one on either update or save.

 

(I've included a few things to make this form work if the user has JavaScript turned off.  The second SELECT MULTIPLE is dynamically rendered using JavaScript as is a hidden form element, useSecondSelect.  The non-JS user can use the single SELECT MULTIPLE as they would normally, you just have to check for the presence of $_POST['useSecondSelect'] in your submission script to see which SELECT MULTIPLE to read from.  The <noscript> tags provide instructions to non-JS users.)  Also, I cut some things out, but this example works perfectly for me.

 

 

A minimal(?) example:

<html>
<head>
<script language="JavaScript1.2">
// Code by Wildbug@phpfreaks, (2006,2007)
// MSIE requires the index (integer) to be passed as the second argument of HTMLSelectElement.add()
// whereas the specification calls for the second argument to be an object.
// This next little bit of code attempts to find out which type the browser expects.

var return_object = false;
try {
	var e = document.createElement('select');
	e.add( document.createElement('option') , 0);
} catch (err) {
	return_object = true;
}

var originalSelection = new Array();

function getInsertionIndex(value,optionList) {
    for (g = 0; g < optionList.length; g++) {
	    if (value - optionList[g].value < 0) {
		    return return_object ? optionList[g] : g;
		}
    }
    return return_object ? optionList[g] : g;
}

function listAdd(fr,to) {

	var e;

	for (i = fr.length - 1; i >= 0; i--) {
		if (fr.options[i].selected) {
			e = document.createElement('option');
			e.text = fr.options[i].text;
			e.value = fr.options[i].value;
			to.add( e , getInsertionIndex(fr.options[i].value,to.options) );
			fr.remove(i);
		}
	}
}

function listRemove(fr,to) {
	// Remove selected from selection and add back into list.

	var e;

	for (i = fr.length - 1; i >= 0; i--) {
		if (fr.options[i].selected) {
			e = document.createElement('option');
			e.text = fr.options[i].text;
			e.value = fr.options[i].value;
			to.add( e , getInsertionIndex(fr.options[i].value,to.options) );
			fr.remove(i);
		}
	}
}

function listRemoveAll(fr,to) {
	// Remove ALL from selection and add back into list.
	var e;

	for (i = fr.length - 1; i >= 0; i--) {
		e = document.createElement('option');
		e.text = fr.options[i].text;
		e.value = fr.options[i].value;
		to.add( e , getInsertionIndex(fr.options[i].value,to.options) );
		fr.remove(i);
	}
}

function selectAll(where) {
	for (i = 0; i < where.length; i++) {
		where.options[i].selected = true;
	}
}

function resetList(fr,to) {
	listRemoveAll(fr,to);

	var arrayCounter = 0;
	var selectCounter = 0;

	while (selectCounter < to.length) {
		if (to.options[selectCounter].value == originalSelection[arrayCounter]) {
			to.options[selectCounter].selected = true;
			arrayCounter++;
		}
		selectCounter++;
	}
	listAdd(to,fr);
}
</script>
</head>
<body>
<?php if(isset($_POST)) echo '<pre>',print_r($_POST,true),'</pre>' ?>
<form action="" method="POST" name="selectform" onSubmit="selectAll(document.selectform.elements['selected_topics[]'])">
<input type=hidden name="action" value="<?php echo isset($user_options) ? 'update' : 'save' ?>">
<select multiple name="topics[]" size=16 style="width:100%">
<?php
/* Some example options */
$all_options = array('A. Option #1','B.  Option #2','C. Third option');
$user_options = array();
$user_options[] = 2;  // User already has something saved.

foreach ($all_options as $key => $value) echo str_repeat("\t",2),"<option value=\"$key\"",in_array($key,$user_options) ? ' selected' : '',">$value\n";

?>
</select>
<noscript>To select more than one item in the above section,
hold down the Ctrl key (PC users) or the Command key (Mac users)
while clicking with the mouse.  To deselect one remaining item,
Ctrl-click on it.</noscript>
<script type="text/javascript">
	document.write('<input type=button value="Add" onClick="listAdd(document.selectform.elements[\'topics[]\'],document.selectform.elements[\'selected_topics[]\'])"> <input type=button value="Remove" onClick="listRemove(document.selectform.elements[\'selected_topics[]\'],document.selectform.elements[\'topics[]\'])"> <input type=button value="Clear List" onClick="listRemoveAll(document.selectform.elements[\'selected_topics[]\'],document.selectform.elements[\'topics[]\'])"> <input type=button value="Reset List" onClick="resetList(document.selectform.elements[\'selected_topics[]\'],document.selectform.elements[\'topics[]\'])"> ');
</script><input type="submit" value="Save"><br><br>
<script type="text/javascript">
	document.write("<b>Your selected topics</b><br><select multiple name=\"selected_topics[]\" size=10 style=\"width: 100%\"></select><input type=hidden name=\"useSecondSelect\" value=\"1\">");
</script>
</form>
<script type="text/javascript">
for (i = 0; i < document.selectform.elements['topics[]'].length; i++) {
	if (document.selectform.elements['topics[]'].options[i].selected) originalSelection.push(document.selectform.elements['topics[]'].options[i].value);
}
listAdd(document.selectform.elements['topics[]'],document.selectform.elements['selected_topics[]']);
</script>
</body></html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.