> 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:
-snip-

       /** {{{2
        * create an INSERT or UPDATE query based on values of an associative array,
        * where keys are the column names to be modified.
        *
        * @param   array    values     an associative array
        * @param   string   table      the table name
        * @param   string   type       the query type, currently only 'INSERT' or
        *                              'UPDATE'
        * @return  mixed   a SQL query string on success, false otherwise (e.g., no
        *                  keys found matching valid column names)
        */
        function array_to_query($values, $table, $type) // {{{3
        {
            if(!is_array($values)) return false;

            foreach($values as $col => $val) {
                $values[$col] = db::quote($val);
                if(is_null($val)) unset($values[$col]);
            }

            switch($type) {

                case 'INSERT':
                    $query = sprintf('INSERT INTO %s (%s) VALUES (%s)', $table, 
join(',', array_keys($values)), join(',', $values));
                    break;

                case 'UPDATE':
                    foreach($values as $col => $val)
                        $values[$col] = " ${col} = ${val}";

                    $query = "UPDATE $table SET " . join(',', $values);
                    break;

                default:
                    trigger_error("Unrecognized query type '$type' supplied to 
db_array_to_query()", E_USER_WARNING);
                    return false;

            }

            return $query;
        }

---------------------------------------------------------------------
michal migurski- contact info and pgp key:
sf/ca            http://mike.teczno.com/contact.html

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

Reply via email to