Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.