Re: Concatenate PHP code into a string
| From: | Torsten Roehr | Date: | Mon, 28 Jun 2004 19:50:50 +0000 |
| Subject: | Re: Concatenate PHP code into a string | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-189178@lists.php.net to get a copy of this message | ||
"Abrea" <abrea@estudiobrea.com> wrote in message
news:WorldClient-F200406281631.AA31300006@estudiobrea.com...
> Dear List,
> How can I include a dynamically generated array:
> e.g. for($i=0; $i<sizeof($cols); $i++)
> { $cols[$i]= mysql_field_name($fields,$i); }
>
> into a MySQL insert query of the type:
> $sql= "INSERT cols[0],cols[1],cols[2], ..., comment
> INTO mytable SET
> cols[0]= '$cols[0]',
> cols[1]= '$cols[1]',
> cols[2]= '$cols[2]',
> cols[...]= '$cols[...]',
> comment= '$comment'";
>
> The number of $cols is different for each table.
> Thanks in advance for any help
>
Hi Alberto,
do your columns change so often that you have to dynamically deal with them?
This requires a DB query every time just to find out the column names!
An easier way would be to setup an array where the key is the column name
and the value is your value to insert. Then you could just do:
$values = array('field1' => 'myValue', 'field2' = 25);
$query = 'INSERT INTO table SET ';
$set = '';
foreach ($values as $column => $value) {
$set .= (empty($set)) ? "$column = '$value'" : ", $column =
'$value'";
}
$query .= $set;
...
Regards, Torsten Roehr