Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extra comma using foreach to create UPDATE sql

Status
Not open for further replies.

vttech

Technical User
Jan 28, 2006
297
US
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?


Code:
        $sql = "UPDATE facform SET ";

	foreach ($_POST as $key => $value) {

		if($key != 'submit' && $value != ''){
		$sql .= "$key = $value, ";
		}
	}

	$sql .= "WHERE id = $id";

Newbie in search of knowledge
 
I think it is easiest to just cut the last few characters off of the $sql before running it.
Code:
    $sql = "UPDATE facform SET ";

    foreach ($_POST as $key => $value) {

        if($key != 'submit' && $value != ''){
        $sql .= "$key = $value, ";
        }
    }

[b][blue]    $sql  = substr ($sql, 0, 2);[/blue][/b]
    $sql .= " WHERE id = $id";
 
How about provision of case where there isn't anything added in the foreach? Like this.
[tt]
$sql = "UPDATE facform SET ";

foreach ($_POST as $key => $value) {

if($key != 'submit' && $value != ''){
$sql .= "$key = $value, ";
}
}

//$sql = substr ($sql, 0, [red]-[/red]2);
$sql = ereg_replace(", $"," ",$sql);
$sql .= "WHERE id = $id";
[/tt]
 
i tend to use trim() or plug the set's into an array and then implode them at the end.
 
I don't think of commas as separators between a series of items. I think of commas as something that precede all but the first item in the series. So my solution for this would be something like:

Code:
$sql = "UPDATE facform SET ";

$first = TRUE;
foreach ($_POST as $key => $value)
{
	if($key != 'submit' && $value != '')
	{
		if ($first != TRUE)
		{
			$sql .= ", ";
		}

		$sql .= $key . " = '" . $value . "'";
	}
	
	$first = FALSE;
}

$sql .= "WHERE id = $id";

vttech:
I would be extraordinarily cautious about using $_POST as you are in this script. You're leaving yourself wide open to users' tampering with what is inserted into your database.



Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top