cedtech31 Posted March 23, 2007 Share Posted March 23, 2007 I am building an sql statement and I am using a foreach loop to create the statement. Everything looks good with the sql statement when I echo it; but the last update field has a comma , that is not needed. How to I account for the last $key => $value set in the array that match my criteria and not have a comma? $sql = "UPDATE facform SET "; foreach ($_POST as $key => $value) { if($key != 'submit' && $value != ''){ $sql .= "$key = $value, "; } } $sql .= "WHERE id = $id"; Quote Link to comment https://forums.phpfreaks.com/topic/43928-solved-extra-comma-in-update-sql-with-foreach/ Share on other sites More sharing options...
btherl Posted March 23, 2007 Share Posted March 23, 2007 You can make an array and then implode it, like this: $sql = "UPDATE facform SET "; $assignments = array(); foreach ($_POST as $key => $value) { if($key != 'submit' && $value != ''){ $assignments[] = "$key = $value"; } } $sql .= implode(', ', $assignments); $sql .= "WHERE id = $id"; Quote Link to comment https://forums.phpfreaks.com/topic/43928-solved-extra-comma-in-update-sql-with-foreach/#findComment-213291 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.