php - How to use foreach to create an array and later update a database -
i have dynamic form populates questionnaire rating scale information saved in database. each rating consists of "selection" , "definition". scale can consists of number or ratings. here example of 5 rating scale:
strongly agree = agree statement. agree = agree statement. neither agree nor disagree = neither agree nor disagree statement. disagree = disagree statement. disagree = disagree statement.
once form populated, user can edit of selections or definitions. form populates fine, cannot figure out how correctly populate post data array if user submits change or use array edit information in database.
here php:
if(isset($_post['submit'])){ $fields = ""; $values = ""; foreach($_post $key => $value) { $fields = mysql_real_escape_string($key); $values = mysql_real_escape_string($value); $entry .= "[". $fields . "=" . $values . "]"; //here start of query i'm building //$query = mysql_query("update `pd_selections` set `pd_selection` = ' ', `pd_definition` = ' ' `pd_selection_id` = '$pd_selection_id' ") or die(mysql_error()); } }
if echo "entry" variable, receive:
[selection_for_1=strongly agree][definition_for_1=i agree statement.][selection_for_2=agree][definition_for_2=i agree statement.]
how pull selection , definition out of array each rating?
how used update database?
am on right track...lol!?
thank can provide.
for security purpose should keep list of keys accept prevent user modifying it, keep people adding non valid data form keeping out fields may not want.
create array selection definition, , use store key/value while checking valid fields:
$accept = array('selection_for_1', 'definition_for_1', 'selection_for_2', 'definition_for_2'); $selection = array(); $definition = array(); foreach ($_post $key => $value) { // if not valid go next field/value if(!in_array($key, $accept)) continue; // if start selection save $selection array // otherwise definition array if (strpos($key, 'selection') !== false) { $selection[] = mysql_real_escape_string($value); } else { $definition[] = mysql_real_escape_string($value); } } // count 1 of array select paired fields // , insert or update database $total = count($definition); ($i=0; $i < $total; $i++) { // update query paired selection , definition $query = mysql_query("update pd_selections set pd_selection = '{$selection[$i]}', pd_definition = '{$definition[$i]}' pd_selection_id = '{$pd_selection_id}'") or echo("could not insert or update selection '{$selection[$i]}', definition '{$definition[$i]}', failed error:", mysql_error()); }
Comments
Post a Comment