Re: Inserting string - need to trim comma

From: Date: Thu, 01 Apr 2004 19:19:57 +0000
Subject: Re: Inserting string - need to trim comma
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-182061@lists.php.net to get a copy of this message
--- Doug Parker <drparker@phreshdesign.com> wrote: > function insert($table, $data) > { > $sql = "INSERT INTO ".$table." SET "; > foreach ($data as $k=>$v) > { > $sql.= $k." = '".$v."', "; > } > $sql.=";"; > $result = mysql_query($sql); > } > > The only problem with the statement is the appended comma to each > iteration - the statement generates a mysql error with the extra comma > at the end of the statement. You can usually avoid this type of problem in the first place with implode(). Something like this (untested): sql = "insert into $table set "; $pairs = array(); foreach ($data as $key => $value) { $pairs[] = "$key = '$value'"; } $sql .= implode(',' $pairs); --- Matt Matijevich <matijevich@alliancetechnologies.net> wrote: > http://www.php.net/rtrim rtrim() trims whitespace, not commas. Hope that helps. Chris ===== Chris Shiflett - http://shiflett.org/ PHP Security - O'Reilly Coming Fall 2004 HTTP Developer's Handbook - Sams http://httphandbook.org/ PHP Community Site http://phpcommunity.org/

« previous php.general (#182061) next »