So after I have created the table ‘settings-table’ i want to add a couple of records to it.
This is how I want to do it, not the best way, so I need a better way to do this because I will add more records to the table.
EXAMPLE 1
$wpdb->insert('settings-table', array('option_name' => 'name-1',
'option_value' => 'val-1',
'option_created'=> current_time('mysql'),
'option_edit' => current_time('mysql'),
'option_user' => 'user-1'
));
$wpdb->insert('settings-table', array('option_name' => 'name-2',
'option_value' => 'val-2',
'option_created'=> current_time('mysql'),
'option_edit' => current_time('mysql'),
'option_user' => 'user-2'
));
$wpdb->insert('settings-table', array('option_name' => 'name-1',
'option_value' => 'val-3',
'option_created'=> current_time('mysql'),
'option_edit' => current_time('mysql'),
'option_user' => 'user-3'
UPDATE
this works(any other better solutions are welcome)
$wpdb->query("INSERT INTO settings-table
(`option_name`, `option_value`, `option_created`, `option_edit`, `option_user`)
VALUES
('name-1', 'val-1', current_time('mysql'), current_time('mysql'), 'user-1'),
('name-2', 'val-2', current_time('mysql'), current_time('mysql'), 'user-2'),
('name-3', 'val-3', current_time('mysql'), current_time('mysql'), 'user-3')")
In the query which you had posted, the column names shouldn’t be in string.
$wpdb->insert function doesn’t support multiple records to be inserted into single function call. You have to loop over your data and prepare the data to be inserted and then use $wpdb->insert into a loop and insert records one by one.
Instead, we can prepare insert query as follow and run a query only once.
So, if we want to insert 100 records, we need to run 100 insert queries if we want to use $wpdb->insert. And if we use following code, we need to run only 1 insert query.
Hope that helps.
I came up with this solution that extends the
wpdb
class so that it uses it’s internal data processing functions:You can then use it like this:
This Will Also Work