Forum Moderators: coopster
I have a file in the MYSQL table named type and I want the name of the type the user selects to go into that field.
My array part of the form looks like this:
<p>Please select a type of incident:
<select name="type[]" multiple>
<option value="disruptive" SELECTED>Disruptive</option>
<option value="accident">Accident</option>
<option value="other">Other</option>
</select>
</p>
The script right now is down to this, (I stripped the serialize function that didn't work):
// Make the array
$type = array('disruptive', 'accident', 'other');
foreach ($type as $key => $value)
//Add the type to the incidents table.
$query = "INSERT INTO incidents (type)
VALUES ('".mysql_escape_string($_POST['type'])."')";
Any help is greatly appreciated.
You may have had troubles serializing since you didn't build up your array with the corresponding $_POST values of your fields (the names of which you put into the array $type). This might work for you. Of course, you have to unserialize this value when you pull it back out of the db, but you probably already knew that.
I've taken a step forward using your help, but I still can't get the name of the selected array element to register in the table. The table field reads a:6:{
no matter which type I select.
I validate using this approach. Any idea what could be missing?
// Check for a type.
$type['disruptive'] = 0;
if ($type['disruptive']) {
echo "true!\n";
}
if (array_key_exists('disruptive', $type)) {
echo "exists!\n";
}
// Make the array
$typearray = array();
$type = array('disruptive', 'accident', 'other');
foreach ($type as $key => $value) {
$typearray[$key] = $_POST[$value]; /* this is the line changed - addition of $key inside the first set of brackets */
}
$typeserialized = serialize($typearray);
//Add the type to the incidents table.
$query = "INSERT INTO incidents (type)
VALUES ('".mysql_escape_string($typeserialized)."')";
With $key missing in $typearray, what this was doing is just adding the values to the array as elements without any 'real' keys. Keys should now be restored. Hope it works now.
Quite simple answer really, you don't have to 'build' the array as the multiple selector named type[] will already come through as an array.
So what you need is this:
if(is_array($_POST['type'])) {
$posttypeserialized = serialize($_POST['type']);
$query = "INSERT INTO incidents (type)
VALUES ('".mysql_escape_string($posttypeserialized)."')";
[ ... ]
}
should you still have some sort of odd problem, you could try conditionally using stripslashes($_POST['type']) before you serialize it if magic_quotes_gpc(); it's been a while since I've used arrays in forms, and I don't know if there would be any issues here with this.
//This is what messed it up.
//$type = array
//('disruptive', 'accident','other');
//This works perfectly:
if(is_array($_POST['type'])) {
$posttypeserialized = serialize($_POST['type']);
$query = "INSERT INTO incidents (type)
VALUES ('".mysql_escape_string($posttypeserialized)."')";