Subtle diagonal pinstripe pattern in light grey and cream, giving an impression of printed editorial paper

Insert and Update WordPress Database Rows Safely

WordPress exposes its database layer through the global $wpdb object. Its insertion and update helpers build parameterised SQL, apply data formats and return values that let code distinguish success from failure. For plugin-owned data, this abstraction supports dependable writes without giving application code unrestricted access to the database.

Many avoidable incidents begin when values are concatenated into SQL or an update lacks a dependable condition. Sanitising input is useful, but it does not replace parameter binding, and escaping cannot repair an unsafe statement. A safe write controls values with placeholders, restricts structural elements to trusted choices, and validates each value according to its business purpose.

Safe use of the WordPress database class for inserting and updating rows also means choosing the correct WordPress layer. Core APIs such as update_option() and update_post_meta() trigger hooks and maintain caches, so they remain preferable for their own data. Direct $wpdb calls suit a plugin-owned store or an operation those APIs cannot express.

Know the data and the platform contract

$wpdb is loaded for normal WordPress requests and provides properties such as $wpdb->prefix, which identifies a site-specific schema. On multisite, $wpdb->base_prefix refers to network-wide storage, while switching blogs changes the relevant site prefix. Never accept either prefix from a request. Use the property supplied by WordPress so a query reaches the intended tenant.

Before writing, define what each field means and which values are allowed. Use absint() for an integer identifier, sanitize_text_field() for a single-line string, and sanitize_textarea_field() for plain multiline text. wp_unslash() may be needed on data taken from a form request because WordPress adds slashes to superglobal values. Validation should reject missing or oversized content rather than quietly repairing it.

Placeholders carry values; they do not decide which fields exist. Match the format array to the data: %d for integers, %f for decimals and %s for strings. Do not let a request choose a column name, sort direction, status expression or SQL fragment. If several fields are possible, map a fixed key such as email to a known database column inside your code.

Keep the storage definition under version control and apply changes through a migration or dbDelta during controlled activation or upgrade, never by editing production storage by hand. Use explicit column definitions and indexes for identifiers searched frequently. Schema changes can be more disruptive than a single insert, so schedule them, back up first and test them against representative records.

Insert rows with controlled inputs

$wpdb->insert() is the normal way to create one record. This example assumes the plugin created its customer_notes structure during activation:

function acme_add_customer_note( $customer_id, $raw_note ) {
    global $wpdb;

    $customer_id = absint( $customer_id );
    $raw_note    = is_string( $raw_note ) ? $raw_note : '';
    $note        = sanitize_textarea_field( wp_unslash( $raw_note ) );

    if ( ! $customer_id || '' === trim( $note ) ) {
        return new WP_Error( 'invalid_note', 'Customer and note are required.' );
    }

    $inserted = $wpdb->insert(
        $wpdb->prefix . 'customer_notes',
        array(
            'customer_id' => $customer_id,
            'note'        => $note,
            'created_at'  => current_time( 'mysql', true ),
        ),
        array( '%d', '%s', '%s' )
    );

    if ( false === $inserted ) {
        return new WP_Error( 'note_insert_failed', 'The note could not be saved.' );
    }

    return array(
        'note_id' => (int) $wpdb->insert_id,
        'rows'    => (int) $inserted,
    );
}

The third argument tells wpdb how to encode each value. A successful call returns the number of inserted records; false signals an error. Check false before using the result, then read $wpdb->insert_id if the caller needs the generated identifier. Catching false prevents a failed write from being mistaken for a successful one.

The format list follows the order of the data array, so a mismatch can assign the wrong type even when placeholders prevent injection. If a value is already normalised, pass it through the helper rather than building SQL by hand. The helper does not supply missing defaults or bypass uniqueness constraints.

An insert does not repair a duplicate. Give required identifiers a unique constraint in the schema and handle the resulting error deliberately; an upsert may be appropriate when duplicate input means “update the existing record.” Avoid $wpdb->replace() for this purpose because it can delete and recreate a record, triggering different behaviour and losing the original identity.

Update rows with precise conditions

Use $wpdb->update() when the change is a simple set of values for an existing record. Keep the condition narrow, and give the method separate format arrays for changed values and condition values:

$note_id = isset( $request['note_id'] )
    ? absint( $request['note_id'] )
    : 0;

$raw_note = isset( $request['note'] ) && is_string( $request['note'] )
    ? $request['note']
    : '';

$note = sanitize_textarea_field( wp_unslash( $raw_note ) );

if ( ! $note_id || '' === trim( $note ) ) {
    return new WP_Error( 'invalid_note', 'A valid customer note is required.' );
}

$updated = $wpdb->update(
    $wpdb->prefix . 'customer_notes',
    array(
        'note'       => $note,
        'updated_at' => current_time( 'mysql', true ),
    ),
    array( 'id' => $note_id ),
    array( '%s', '%s' ),
    array( '%d' )
);

The return value has three meaningful states: false means the statement failed, 0 means that no row changed, and a positive integer gives the number of affected rows. A record can contain the requested values already, so zero is not automatically an error. It is also not proof that the intended record exists.

The fourth and fifth arguments matter: the first describes changed values and the second describes condition values. Omitting formats lets WordPress infer them, but explicit formats make reviews easier and avoid surprises with numeric strings. Keep the condition on a unique key; if a broader update is genuinely intended, first select the permitted identifiers and document why each one qualifies.

For a conditional or multi-field statement, call $wpdb->prepare() with placeholders and pass every value separately. For example, a status change can require the current status to match:

$sql = "UPDATE {$wpdb->prefix}customer_notes SET status = %s WHERE id = %d AND status = %s";

$changed = $wpdb->query(
    $wpdb->prepare( $sql, 'closed', $note_id, 'open' )
);

This prevents one request from closing a record another request has already handled. Structural SQL comes only from trusted code, while request data remains in placeholders.

Combine writes with transactions and error handling

Several related changes can be grouped with a database transaction. Start before the first write, commit only after every required step succeeds, and roll back when a later step fails:

$wpdb->query( 'START TRANSACTION' );

$inserted = $wpdb->insert( /* prepared values */ );

if ( false === $inserted ) {
    $wpdb->query( 'ROLLBACK' );
} else {
    $wpdb->query( 'COMMIT' );
}

A transaction provides atomicity only when the affected storage uses a transactional engine such as InnoDB. Check the plugin’s schema before relying on rollback behaviour, and keep schema changes outside the transaction because MySQL may commit implicitly around them. Email sends, payment calls and filesystem writes also sit outside the database transaction, so the application still needs compensation or retry logic.

Diagnose failures with $wpdb->last_error and $wpdb->last_query, especially in development with WP_DEBUG enabled. Log the operation, affected identifier and safe error context, but redact addresses, tokens, payment details and other sensitive values before sending logs or SQL to a monitoring service. Never show raw database errors to visitors.

wpdb normally reports database failures through return values rather than automatically throwing exceptions, so each call inside a transaction must still be checked. An exception from PHP code can leave the transaction open unless a finally block rolls it back. Test both successful and forced-failure paths, and make retries idempotent so a repeated request does not duplicate records.

Integrate direct writes with WordPress

A successful SQL statement can still leave WordPress holding stale data. Core APIs fire actions and invalidate relevant caches; a direct write normally does not. Use update_option() for options, update_post_meta() for metadata and post APIs for post fields. When custom data is necessary, invalidate the specific object-cache entry and fire any documented action so other parts of the plugin see a consistent state.

Before changing production data, work through a short preflight:

After the write, complete a second brief review:

Apply Australian deployment and support checks

Australian WordPress teams commonly serve organisations in Sydney, Melbourne, Brisbane and Perth, using a mixture of local-region hosting and overseas infrastructure. WooCommerce stores may hold customer details, delivery addresses and AUD invoices, often with GST applied to taxable supplies. Under the Australian Consumer Law, prices and representations shown to customers must be accurate, so order and financial records deserve the same change controls as any other production data.

Where the Privacy Act 1988 and Australian Privacy Principles apply, personal information should be handled consistently with its purpose and protected with reasonable safeguards. A database log should identify an administrative action without becoming a second copy of a customer’s full profile. The legislation does not create a blanket requirement to keep every WordPress database in Australia, but contracts and client policies can still make residency, retention and access controls important.

Store timestamps in UTC by using current_time( 'mysql', true ). Daylight saving dates differ across Australian states, and Western Australia does not observe the shift, so code should not assume a fixed offset from AEST. WP-Cron also depends on site time and incoming traffic; time-sensitive jobs need a reliable scheduler rather than an assumption that every request arrives on time.

Troubleshoot from the narrowest safe step: reproduce on staging, inspect the affected record, review the error and then retry. The team behind Livewire Karur support can provide a second review of query structure, error handling and plugin integration before production deployment. Keep credentials out of tickets and redact personal data from examples.

Operation Preferred method Return signal Strongest use Main caution
Create one record $wpdb->insert() Inserted count or false Plugin-owned records Validate values and handle duplicate constraints
Change known fields $wpdb->update() Affected count, zero or false Existing record updates Always use a scoped condition
Run custom SQL $wpdb->query( $wpdb->prepare(...) ) Affected count or false Conditional or multi-field changes Structural SQL must be trusted
Manage WordPress data update_option() or update_post_meta() API-specific success value Options and metadata Prefer hooks and cache handling