Got a small problem regarding saving my form to the database and imploding. The issue is as following:
I have a form which has multiple fields, including checkboxes, which has an array of values. If I send the whole form to my php script it strips the checkbox value with the last one checked, so the issue is, I only get the last checked value in my database instead of all the checked values.
So I did a bit of debugging and I found the issue, it's in this line:
$values = "'" . implode("', '", $_POST) . "'";
This strips my data unfortunately.
EDIT:
This is my PHP script:
$hoeveelheidvalues = count($_POST);
$values = "'" . implode("', '", $_POST) . "'";
$queryvoorderesperform = "INSERT INTO `app_res_per_form` (";
for($i = 1; $i <= $hoeveelheidvalues; $i++)
{
if($i==$hoeveelheidvalues)
{
$queryvoorderesperform .= "vraag$i";
}
else{
$queryvoorderesperform .= "vraag$i, ";
}
}
$queryvoorderesperform .= ") VALUES ($values)";
EDIT 2:
If I use serialize I get a very weird string. This is the $queryvoorderespform:
INSERT INTO `app_res_per_form` (vraag1, vraag2, vraag3, vraag4, vraag5, vraag6, vraag7, vraag8, vraag9, vraag10, vraag11, vraag12)
VALUES (a:12:{s:16:"multipleradios-0";s:11:"Orientation";s:11:"textinput-0";s:0:"";s:20:"multiplecheckboxes-0";s:9:"Recycling";s:11:"textinput-1";s:0:"";s:10:"interestin";s:15:"Diverter Valves";s:12:"rotaryvalves";s:7:"AL, AXL";s:14:"divertervalves";s:3:"PTD";s:15:"othercomponents";s:3:"DUC";s:11:"textinput-3";s:0:"";s:16:"multipleradios-1";s:18:"Systems Integrator";s:16:"multipleradios-2";s:38:"Will buy product in long time (1 year)";s:15:"standcrewmember";s:13:"Aap";})
You can use serialize()
, its a PHP function to convert an array or object into a string that can then be re-hydrated back into an array or object using unserialize();
$values = serialize($_POST);
or better still save the contents of $_POST as JSON using
$values = json_encode($_POST);
and re-hydrate into an array or object using
$var = json_decode($x);
These can be used on PHP Arrays or PHP Objects.
Ok now I see what you are actually trying to do so try this :-
$fields = '';
$values = '';
$count = 0;
foreach ( $_POST as $idx => $val ) {
// I assume you are skipping occurance 0 for a reason
if ( $count == 0 ) {
$count++;
continue;
}
$fields .= sprintf('vraag%d,', $count );
$values .= sprintf("'%s',", $val );
$count++;
}
//trim off trailing commas
rtrim($fields, ',');
rtrim($values, ',');
$sql = sprintf('INSERT INTO `app_res_per_form` (%s) VALUES (%s)',
$fields, $values);
}
Oh and I assume you are using the MYSQL_ extension! Someone is going to tell you not to and to switch to MYSQLI_ or PDO. So it may as well be me.