WordPress.org

Make WordPress Core

Opened 9 months ago

Last modified 9 months ago

#45936 new defect (bug)

Insert empty record

Reported by: maximeschoeni Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: General Keywords: reporter-feedback
Focuses: Cc:
PR Number:

Description

I fall upon a small bug when trying to insert an empty record in a custom table. To reproduce, just create a basic table 'my_table' and use this code:

$wpdb->insert( 
  'my_table'
  array(),
  array()
);

which produce this mysql:

"INSERT INTO `my_table` (``) VALUES ()"

which throw an error. So instead I would like it produces this result:

"INSERT INTO `my_table` () VALUES ()"

Which would just achieve the expected result: create an empty record.

Now the fixing is very easy:

just replace this line (/wp-include/wp-db.php line 2087, _insert_replace_helper function)

$fields  = '`' . implode( '`, `', array_keys( $data ) ) . '`';

by

$fields  = $data ? '`' . implode( '`, `', array_keys( $data ) ) . '`' : '';


Change History (2)

#1 @subrataemfluence
9 months ago

  • Keywords reporter-feedback added

Your suggestion does fix the issue of inserting empty record.
But what could be a working situation where you might need to insert an empty record? An example would be good.

Also if a numeric Primary Key is present in the table and it is not auto incremental, trying to insert multiple empty records will throw duplicate primary key error.
Because it will try to add 0 in the primary key.

#2 @maximeschoeni
9 months ago

Of course it makes no sense to insert an empty record if the table doesn't have an auto-incremental primary key.

As an example, what's about some kind of post you would want to relate to a category before setting other fields, maybe with AJAX or REST?

Note: See TracTickets for help on using tickets.