pets2soul Posted March 16, 2011 Share Posted March 16, 2011 Dear experts, I'm working on a user info updating form, and I only want the amended fields to be updated to the database, I figured this part out, however what caught me is the updating part, where my amended values are stored in an array, and I'm trying to put the values into the SET part with the use of FOR loop, but I can't get the query to work properly...it'd be super duper thankful if anyone can help me with it. Below is my code: $diff_num = count($diff_info); $diff_value = array_values($diff_info); $diff_key = array_keys($diff_info); for($i = 0; $i < $diff_num; $i++) { $db_update = "AND " . $diff_key[$i] . " = '" . $diff_value[$i] . "' "; $query = "UPDATE db_table SET field_one = '$value_one' " . $db_update . " WHERE field_some = '$value_some'"; if (mysql_query($query)) { return true; } else { return false; } } Quote Link to comment https://forums.phpfreaks.com/topic/230794-update-syntax-in-for-loop/ Share on other sites More sharing options...
kickstart Posted March 16, 2011 Share Posted March 16, 2011 Hi No need to split the array and then do a for loop. You can just use foreach <?php if (count($diff_info) > 0) { $db_update = ''; foreach($diff_info AS $diff_key=>$diff_value) { $db_update .= ", $diff_key = '" . mysql_real_escape_string($diff_value) . "' "; } $query = "UPDATE db_table SET field_one = '$value_one' " . $db_update . " WHERE field_some = '$value_some'"; if (mysql_query($query)) { return true; } else { return false; } } return false; // nothing to update! ?> Something like that should do it All the best Keith Quote Link to comment https://forums.phpfreaks.com/topic/230794-update-syntax-in-for-loop/#findComment-1188136 Share on other sites More sharing options...
pets2soul Posted March 17, 2011 Author Share Posted March 17, 2011 Dear Keith, Thank you very much! It worked out perfectly! And this is my first time using Foreach, feels good to learn a new thing! Best Regards, AJ Quote Link to comment https://forums.phpfreaks.com/topic/230794-update-syntax-in-for-loop/#findComment-1188514 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.