Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
VGSources
Blog

How to Prevent SQL Injection Attacks in WordPress

A practical WordPress guide to preventing SQL injection: prefer native APIs, prepare every value, handle LIKE safely, and allowlist dynamic SQL structure.
WorldWordPress Length5 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prevent SQL injection in WordPress by avoiding hand-written SQL when a native WordPress API can do the job. When custom SQL is necessary, pass every data value through $wpdb->prepare() immediately before execution, use a placeholder that matches the value’s type, and build dynamic table names, column names, sort directions, and other SQL structure from a fixed allowlist. esc_sql() is useful in limited situations, but it is not a substitute for prepared statements.

The key distinction is between values supplied to a query and the query’s structure. Prepared placeholders protect values. They do not make arbitrary SQL keywords, operators, identifiers, or clauses safe. Those structural choices must be fixed in code or selected from an allowlist.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What SQL injection means in a WordPress site

SQL injection occurs when untrusted input changes the meaning of a database query. A plugin, theme, or custom endpoint is at risk when request data is concatenated into SQL and the resulting text is executed as one statement. An attacker may submit input containing quotes, operators, comments, or other SQL syntax instead of the ordinary value the feature expects.

WordPress gives developers a safer database interface through the global $wpdb object, but it does not automatically make custom SQL safe. The WordPress database reference states that all data in SQL queries must be SQL-escaped before execution. The Theme Handbook’s first rule for hardening a theme against SQL injection is to use a WordPress function whenever one exists.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

In practice, protection has four parts:

  • Use a native WordPress API for an operation it already supports.
  • Normalize or reject input before constructing a query.
  • Put every value into a correctly typed, unquoted placeholder.
  • Keep SQL structure out of user control by using %i where supported or a strict allowlist.

Prefer a native WordPress API before writing SQL

Custom SQL creates responsibilities that a WordPress API has already handled: selecting the right table, formatting values, escaping data, and returning results in an expected form. Before writing a query, check whether the operation can be performed with a core API or a standard query object.

Examples of safer first choices

  • Use post, page, or custom-post-type query APIs instead of directly querying the posts tables.
  • Use the user, comment, term, or metadata APIs instead of assembling joins against their tables.
  • Use WordPress option and setting APIs for site configuration data.
  • Use a core function that performs the required lookup, update, insertion, or deletion instead of reproducing it with SQL.

A native API is not a license to skip validation. Continue to validate permissions, expected types, and business rules. The security advantage is that you avoid exposing a new SQL construction path when WordPress already provides one.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use $wpdb->prepare() for custom SQL values

For a custom query, construct the SQL template and provide values separately to $wpdb->prepare(). Prepare the statement as close as possible to execution, then pass the prepared string to a method such as get_col(), get_results(), get_row(), get_var(), query(), or getที่?.

Here is a complete value-query pattern:

<?php
global $wpdb;

$user_id = absint( $_GET['user_id'] ?? 0 );
$status = sanitize_key( $_GET['status'] ?? 'publish' );

$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_author = %d AND post_status = %s",
$user_id,
$status
);

$ids = $wpdb->get_col( $sql );

absint() turns the requested user ID into a non-negative integer. sanitize_key() normalizes a key-like status value; your code should still restrict it to statuses the feature actually supports. The query then places the integer in %d and the string in %s.

Choose the placeholder by data type

Placeholder Use it for Important constraint
%s Strings Keep it unquoted in the SQL template.
%d Integers Convert or validate the input as an integer before preparing.
%f Floating-point numbers Validate the expected numeric range and precision separately.
%i Identifiers such as table or field names Use only on WordPress versions that support it; it is not a value placeholder.

Placeholders must not be wrapped in quotes. Write WHERE post_status = %s, not WHERE post_status = '%s'. WordPress supplies the required quoting and escaping for value placeholders.

Literal percent signs

A percent sign that is part of the SQL text rather than a placeholder must be doubled as %%. This prevents prepare() from treating the percent sign as a formatting token.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Safely search with LIKE

For a partial text search, escape the search text with esc_like(), add the wildcard characters to the argument, and then pass the complete pattern through a string placeholder.

<?php
global $wpdb;

$needle = '%' . $wpdb->esc_like( $search_term ) . '%';

$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_title LIKE %s",
$needle
);

$ids = $wpdb->get_col( $sql );

Do not put the wildcards around the placeholder in the SQL template and do not concatenate the raw search term into the query. esc_like() handles characters that have special meaning in a SQL LIKE pattern; prepare() then handles the value as a string.

Validate and normalize input before query construction

Prepared statements protect the SQL boundary, but they do not decide whether an input is appropriate for your feature. Normalize each request value to the type and range the operation expects.

Integer input

Use an integer conversion such as absint() for IDs that cannot be negative. If zero is not a valid ID, reject it before querying. For counts, offsets, or limits, enforce a sensible maximum in your application logic rather than allowing an arbitrary number to control the query.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Key-like strings

For values such as a post status, mode, or action key, normalize the input and compare it with the finite set your feature supports. A sanitizer alone does not turn an unknown value into a valid business choice.

Enumerated choices

When the input selects one of several behaviors, map each accepted token to a value defined in code. Reject everything else. This pattern is especially important for sort fields, sort directions, table choices, operators, and optional clauses because those items are SQL structure rather than ordinary data.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Dynamic table and column names

Values and identifiers are different. A post title is a value and belongs in %s. A table name or column name changes the SQL statement’s structure and cannot be treated as an ordinary string value.

Use %i on supported WordPress versions

WordPress documents the %i placeholder for identifiers such as table and field names. It was added in WordPress 6.2.0. On a supported version, an identifier can be supplied separately from the query template:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
global $wpdb;

$table = $wpdb->prepare(
'SELECT COUNT(*) FROM %i WHERE owner_id = %d',
$custom_table,
$owner_id
);

$count = $wpdb->get_var( $table );

The identifier still must come from a trusted choice in your application. %i is not interchangeable with %s, and it should not be used as a way to accept arbitrary request text as a table or field name.

Use an allowlist for older versions

If your plugin supports WordPress versions before 6.2.0, do not interpolate a request parameter directly into SQL. Map a small set of accepted keys to fixed identifiers:

<?php
global $wpdb;
'posts' => $wpdb->posts,
'terms' => $wpdb->terms,
);

if ( ! isset( $tables[ $table_key ] ) ) {
return;
}
$sql = $wpdb->prepare(
"SELECT COUNT(*) FROM {$table_name} WHERE term_id = %d",
$term_id
);

Here, the request can choose only between identifiers already present in the array. It cannot supply punctuation, whitespace, a second table, or an SQL fragment.

Make ORDER BY, directions, and operators explicit

Sort columns and directions are common sources of unsafe concatenation because they are not ordinary values. A query such as ORDER BY {$requested_column} {$requested_direction} is unsafe if either variable contains request data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Instead, map the user’s choice to fixed SQL fragments:

<?php
$sort_columns = array(
'title' => 'post_title',
'date' => 'post_date',
);

$directions = array(
'asc' => 'ASC',
'desc' => 'DESC',
);
$direction_key = sanitize_key( $_GET['dir'] ?? 'desc' );

$sort_column = $sort_columns[ $sort_key ] ?? $sort_columns['date'];
$direction = $directions[ $direction_key ] ?? $directions['desc'];

$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} ORDER BY {$sort_column} {$direction} LIMIT %d",
$limit
);

The allowlist controls the SQL words that are inserted. The limit remains a numeric value and is supplied through %d. The same approach applies to operators, optional clauses, and database actions: choose from constants in code rather than allowing raw request text to become SQL syntax.

Why esc_sql() is not enough

esc_sql() has a narrower purpose than many developers assume. Its reference recommends $wpdb->prepare() in general and warns that esc_sql() does not escape unquoted numeric values, field names, or SQL keywords.

That means this pattern is not a complete defense:

$sql = "SELECT ID FROM {$wpdb->posts} WHERE post_author = " . esc_sql( $user_id );

The numeric value is still being assembled into SQL text rather than passed through a typed placeholder. A field name or keyword passed to esc_sql() is not made safe merely because it was escaped. Cast numeric data, allowlist identifiers and SQL keywords, and keep ordinary values in %s, %d, or %f placeholders.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Prepare immediately before execution

WordPress coding standards recommend escaping as close to the query as possible, preferably with $wpdb->prepare(). Keeping preparation next to execution makes it easier to audit the final query and reduces the chance that another code path modifies or reuses an unprepared string.

  1. Read the request or function arguments.
  2. Normalize each value to its expected type.
  3. Resolve every structural choice through constants or an allowlist.
  4. Build the SQL template with placeholders.
  5. Call $wpdb->prepare() immediately before the database method.
  6. Execute the prepared query and handle an empty or error result according to the feature’s contract.

Review every concatenation in a custom query. A query can contain safe placeholders and still be vulnerable if one table name, column, clause, or operator is inserted from uncontrolled text.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Version support you must account for

WordPress version detail What it means for your code
%i was added in WordPress 6.2.0. Use it for identifiers only when your supported version range includes the implementation; otherwise use a fixed allowlist.
WordPress documents an unsafe-query issue affecting version 4.8.2 and earlier. Set and communicate a supported WordPress range, and do not assume legacy placeholder behavior matches current releases.

If your plugin must run on older installations, test its database layer against the oldest supported WordPress version. Keep compatibility code explicit rather than silently relying on a placeholder that the oldest version does not understand.

Common unsafe patterns and their repairs

Concatenating a request value

Unsafe:

$sql = "SELECT ID FROM {$wpdb->posts} WHERE ID = " . $_GET['id'];

Repair:

$id  = absint( $_GET['id'] ?? 0 );
$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
$id
);

Quoting a placeholder manually

Unsafe:

$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_status = '%s'",
$status
);

Repair:

$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_status = %s",
$status
);

Putting a wildcard around the placeholder

Unsafe:

$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_title LIKE '%s%'",
$search_term
);

Repair:

$needle = '%' . $wpdb->esc_like( $search_term ) . '%';
$sql = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_title LIKE %s",
$needle
);

Accepting an arbitrary sort field

Unsafe:

$sql = "SELECT ID FROM {$wpdb->posts} ORDER BY " . $_GET['sort'];

Repair: map accepted sort keys such as title and date to fixed column names, then insert only the mapped value. If the selected identifier is passed as a parameter on WordPress 6.2.0 or later, use %i; otherwise retain the allowlist mapping and never interpolate the raw request value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Audit checklist for a plugin or theme

  • Search for $wpdb, SELECT, INSERT, UPDATE, DELETE, and string concatenation near SQL.
  • Confirm that a native WordPress API cannot perform each operation.
  • Check every value for a matching %s, %d, or %f placeholder.
  • Verify that placeholders are not surrounded by quotes.
  • Check LIKE searches for esc_like() and argument-side wildcards.
  • Identify every dynamic table name, field name, sort direction, operator, and optional clause.
  • Confirm that each structural choice is a constant, a supported %i identifier, or a fixed allowlist entry.
  • Check that numeric values are cast or validated rather than escaped as strings.
  • Ensure preparation happens immediately before the execution method.
  • Test the oldest WordPress version your plugin claims to support, especially if it predates 6.2.0.

Diagnosing a query that still fails review

The query contains a placeholder but remains unsafe

Look for a second concatenation. A prepared value does not protect an untrusted table name, column, direction, keyword, or clause added elsewhere in the same SQL string.

A search returns no expected matches

Check that the wildcard characters were included in the argument and that the search text passed through esc_like(). Also confirm that the placeholder remains %s without manual quotes.

A legacy installation reports a placeholder problem

Check the plugin’s minimum WordPress version. If the code relies on %i, installations older than 6.2.0 require a compatibility path using a fixed allowlist instead.

A sort option changes the query unexpectedly

Inspect the mapping table, not just the request sanitizer. The accepted external key should resolve to one of a small number of complete, known column or direction values. Unknown keys should be rejected or assigned a safe default.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical decision framework

  1. Can WordPress perform this operation? Use the native API and avoid SQL.
  2. Is the input a value? Normalize it and pass it through the matching typed placeholder.
  3. Is the input an identifier or SQL fragment? Resolve it from code-defined choices; use %i for supported identifier handling, or an allowlist for older versions.
  4. Does the query contain a pattern search? Escape the pattern with esc_like(), add wildcards to the argument, and prepare it as %s.
  5. Does the supported WordPress range include older releases? Verify placeholder behavior against the minimum version and retain a legacy-safe path where necessary.

This framework answers the central question: $wpdb->prepare() is essential for values, but it is not the only control. Safe SQL also depends on choosing the right WordPress API, validating types, and preventing request data from becoming query structure.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.