Jump to content

[SOLVED] extra comma in update sql with foreach


cedtech31

Recommended Posts

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";

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";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.