Search code examples
mysqlinsert

Skip column when inserting into MySQL


How can I skip a column when inserting a new row into a table without knowing neither the names nor the amount of columns in my table?

Using INSERT (col1, col2) VALUES (1, 2) is not an option, because I can not know the amount of columns during runtime. It's all calculated from user input.

Thus, I need to skip the first column (id, PRIMARY KEY auto_increment) when inserting.


Solution

  • You can insert without giving column names, but you had to give some values for all columns.

    INSERT INTO comments 
    VALUES (null, 2, 3, 4,null,6) 
    
    CREATE TABLE IF NOT EXISTS `comments` (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `imageid` int(10) unsigned NOT NULL DEFAULT '0',
      `uid` bigint(20) unsigned NOT NULL DEFAULT '0',
      `content` text CHARACTER SET utf8,
      `adate` datetime DEFAULT NULL,
      `ip` int(10) unsigned DEFAULT NULL,
      PRIMARY KEY (`id`),
       KEY `ids` (`imageid`,`adate`) USING BTREE
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1  ;