Opened 7 years ago
Closed 6 weeks ago
#45936 closed defect (bug) (invalid)
Insert empty record
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Milestone: | Awaiting Review | Priority: | normal |
| Severity: | normal | Version: | |
| Component: | General | Keywords: | |
| Focuses: | Cc: |
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 (3)
#2
@
7 years 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?
#3
@
6 weeks ago
- Keywords reporter-feedback removed
- Resolution set to invalid
- Status changed from new to closed
Hi all,
It's been 7 years since this ticket was opened, requesting the ability to insert blank records via wpdb. We haven't had any additional requests for this, and I believe it's generally considered undesirable behavior to add empty rows. Looking at the use case mentioned, it would probably be better to insert a row with whatever data you have, and then update it afterwards when you get the rest of the data.
I'm going to close this ticket to help clean up Trac, but feel free to discuss and reopen if you feel this is critical for WordPress.
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 Keyis 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
0in the primary key.