How to Use $wpdb Safely for Custom Queries in WordPress

What-is-wpdb-in-WordPress

What is $wpdb in WordPress?

$wpdb is WordPress’s built-in database access class that allows developers to interact with the database directly using SQL queries. It gives you the power to select, insert, update, and delete data in a secure way while respecting WordPress’s database structure.

global $wpdb;
$results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE post_status = 'publish'");

Why You Must Use $wpdb Safely

Direct SQL queries can expose your website to SQL injection attacks if not handled properly. WordPress provides methods like $wpdb->prepare() to sanitize values before running queries.

Unsafe example ❌:

$results = $wpdb->get_results("SELECT * FROM wp_users WHERE ID = $_GET[id]");

This is unsafe because the $_GET parameter is directly injected.

Safe example ✅:

$id = intval($_GET['id']);
$results = $wpdb->get_results( $wpdb->prepare(
    "SELECT * FROM {$wpdb->users} WHERE ID = %d", $id
));

Common $wpdb Methods (with Examples)

$wpdb->get_results() – Fetch Multiple Rows

global $wpdb;
$posts = $wpdb->get_results(
    "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_status = 'publish'"
);

foreach ($posts as $post) {
    echo $post->post_title . "<br>";
}

Fetch a Single Row – $wpdb->get_row()

$user = $wpdb->get_row( $wpdb->prepare(
    "SELECT * FROM {$wpdb->users} WHERE ID = %d", 1
) );

echo $user->user_email;

$wpdb->get_var() – Fetch a Single Value

$post_count = $wpdb->get_var(
    "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'publish'"
);

echo "Total published posts: " . $post_count;

Insert Data with $wpdb->insert()

$wpdb->insert(
    "{$wpdb->prefix}custom_table",
    array(
        'name'  => 'John Doe',
        'email' => 'john@example.com',
    ),
    array('%s', '%s') // data formats
);

Update Data with $wpdb->update()

$wpdb->update(
    "{$wpdb->prefix}custom_table",
    array('email' => 'newemail@example.com'),
    array('id' => 5),
    array('%s'),
    array('%d')
);

Delete Data with $wpdb->delete()

$wpdb->delete(
    "{$wpdb->prefix}custom_table",
    array('id' => 10),
    array('%d')
);

Best Practices for Using $wpdb

  1. Always use $wpdb->prepare() to sanitize queries.
  2. Use $wpdb->prefix or $wpdb->tablename instead of hardcoding table names.
    • Example: use {$wpdb->posts} instead of wp_posts.
  3. Validate and sanitize user inputs with intval(), sanitize_text_field(), etc.
  4. Use correct format specifiers in queries:
    • %d → Integer
    • %s → String
    • %f → Float
  5. Limit query results with LIMIT to avoid performance issues.
  6. Escape output when displaying results (esc_html(), esc_attr()).

Final Thoughts

Using $wpdb safely in WordPress gives you the flexibility to run custom queries while keeping your site secure and optimized. Always sanitize inputs, use $wpdb->prepare(), and follow best practices to avoid SQL injection risks.

By mastering $wpdb, you can build custom features, reports, and integrations without relying on extra plugins.

Looking for more WordPress coding tips? Check out our WordPress Development Tutorials for more practical guides.