Re: Inserting string - need to trim comma
| From: | Doug Parker | Date: | Thu, 01 Apr 2004 19:26:15 +0000 |
| Subject: | Re: Inserting string - need to trim comma | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-182064@lists.php.net to get a copy of this message | ||
implode() worked perfectly.
thanks -
doug
----- Original Message -----
From: "Chris Shiflett" <shiflett@php.net>
To: "Doug Parker" <drparker@phreshdesign.com>; <php-general@lists.php.net>
Sent: Thursday, April 01, 2004 2:19 PM
Subject: Re: [PHP] Inserting string - need to trim comma
> --- 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/