Re[2]: [PHP] Inserting string - need to trim comma

From: Date: Fri, 02 Apr 2004 02:17:55 +0000
Subject: Re[2]: [PHP] Inserting string - need to trim comma
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-182081@lists.php.net to get a copy of this message
Hi, Friday, April 2, 2004, 5:10:29 AM, you wrote: MM> <snip> MM> function insert($table, $data) { MM> $sql = "INSERT INTO ".$table." SET "; MM> foreach ($data as $k=>$v) { MM> $sql.= $k." = '".$v."', "; MM> } MM> $sql.=";"; MM> $result = mysql_query($sql); MM> } MM> The only problem with the statement is the appended comma to each MM> iteration - the statement generates a mysql error with the extra comma MM> at MM> the end of the statement. This seems like an easy fix -any ideas? MM> Any help would be greatly appreciated... MM> </snip> MM> http://www.php.net/rtrim Change the logic slightly: function insert($table, $data) { $set = ''; foreach ($data as $k=>$v) { $set .= (empty($set))? '',', '; //only need comma if not empty $set .= $k." = '".$v."'"; } if(!empty($set){ $sql = "INSERT INTO ".$table." SET ".$set; $result = mysql_query($sql); } } -- regards, Tom

« previous php.general (#182081) next »