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"; 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"; 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
Archived
This topic is now archived and is closed to further replies.