"Abrea" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> 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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to