How to insert data using wpdb

How to insert data using wpdb

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Diagnosing the wpdb Insertion Error in WordPress

The code snippet you provided fails because of a fundamental misunderstanding of how WordPress handles SQL prepared statements. The error occurs immediately when $wpdb->query($sql) is executed, not because the data isn't inserted, but because the variable syntax within the prepare() method is broken.

You are passing raw PHP variables directly into the string definition without using the specific placeholders that prepare() expects. When you write:

$sql = $wpdb->prepare(
 "INSERT INTO ... values ("
 $name, $email, ...
 ')' );

WordPress does not substitute $name with "Kumkum" at runtime. Instead, it treats $name as a literal string inside the SQL query or throws a syntax error because the comma-separated values are not wrapped in placeholders. The prepare() method requires you to define the structure of the SQL statement first, using %s for strings and %d for integers, and then pass the actual values as separate arguments.

Correcting the Variable Injection

To fix this, you must restructure your query string to include placeholders for every input value. The corrected logic looks like this:

$name    = 'Kumkum';
$email   = 'kumkum@gmail.com';
$phone   = '3456734567';
$country = 'India';
$course  = 'Database';
$message = 'hello i want to read db';

// Calculate the current timestamp
$now     = new DateTime();
$datesent = $now->format('Y-m-d H:i:s');

global $wpdb;

// Define placeholders for all string values
$sql = $wpdb->prepare(
    "INSERT INTO `wp_submitted_form` 
     (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) 
     VALUES (%s, %s, %s, %s, %s, %s, %s)",
    $name, $email, $phone, $country, $course, $message, $datesent
);

$wpdb->query($sql);

The key change is the introduction of %s in the SQL string. Each %s acts as a slot where WordPress will safely inject the corresponding PHP variable after sanitization. You must ensure the number of %s placeholders exactly matches the number of arguments passed to prepare(). If you miss one or add an extra one, MySQL will return a "Incorrect integer value" or a syntax error regarding column count.

Handling Data Types and Escaping

While your current example uses only strings, it is critical to distinguish between %s (string) and %d (integer). In your specific case, the phone number 3456734567 is technically an integer in many databases, though often stored as text in WordPress tables. If wp_submitted_form defines the phone column as INT, you should use %d:

$sql = $wpdb->prepare(
    "INSERT INTO `wp_submitted_form` 
     (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) 
     VALUES (%s, %s, %d, %s, %s, %s, %s)",
    $name, $email, $phone, $country, $course, $message, $datesent
);

Using the wrong placeholder type can cause silent data corruption. If you insert a string like "3456734567" into an integer column using %s, WordPress will convert it to a number. However, if the column expects strict integer formatting and your input contains hidden characters or is treated as text by the SQL engine, you might face type mismatch errors. Always verify the column definition in your database schema before deciding on the placeholder.

Security Implications of prepare()

The primary reason for using $wpdb->prepare() rather than string concatenation (e.g., $sql = "INSERT ... VALUES ('$name', ...)") is security. Without placeholders, a user who controls any of these input fields could inject malicious SQL code. For instance, if $message contained ' OR '1'='1, a concatenated query would allow unauthorized data access or deletion.

By separating the structure from the data, prepare() automatically escapes the values based on their type. This means you do not need to manually call esc_sql() for every field; prepare() handles that logic internally. However, this only works if you stick to the placeholder syntax strictly. Mixing raw string concatenation with prepare() is a common mistake that defeats the security mechanism entirely.

Troubleshooting the Execution

If you still encounter errors after correcting the syntax, check the return value of $wpdb->query(). While it returns the number of affected rows on success, it often throws a WordPress_Error object if something goes wrong. It is best practice to wrap this in a conditional block:

if ( $wpdb->query( $sql ) === false ) {
    error_log( wp_die( $wpdb->last_error ) );
}

This approach logs the specific database error message, which usually indicates whether the table exists, if the column names are correct, or if there is a primary key conflict. Always ensure the wp_submitted_form table actually exists and that the column names match the schema exactly, including backticks around them if they contain special characters or spaces.

For developers looking to manage complex database interactions with better abstraction layers, resources like https://laravelcompany.com discuss how modern PHP frameworks handle ORM patterns, which can serve as a conceptual comparison for moving beyond raw wpdb queries in larger applications.

Our network