sql-injection-prevention
Skill45 starsChanged 3 months agoMITView on GitHub
Use when writing any custom database query in WordPress with $wpdb — get_results, get_var, get_row, query, or building WHERE/IN/LIKE/ORDER BY clauses. Uses $wpdb->prepare() with correct placeholders (%d, %s, %f, %i), $wpdb->esc_like() for LIKE, and allowlists for identifiers that cannot be parameterized. Prevents SQL injection. Apply proactively to every query containing a dynamic value.
In this repository26 other files it gives its agents.
- ai-llm-integration-securitySkill
- ajax-securitySkill
- authentication-session-securitySkill
- capability-permission-checksSkill
- cron-background-job-securitySkill
- dependency-supply-chain-securitySkill
- filesystem-securitySkill
- file-upload-securitySkill
- gutenberg-block-editor-securitySkill
- http-api-ssrf-preventionSkill
- input-sanitization-validationSkill
- multisite-securitySkill
- nonces-csrf-protectionSkill
- object-injection-deserializationSkill
- output-escapingSkill
- rest-api-securitySkill
- secrets-credentials-managementSkill
- secure-plugin-developmentSkill
- security-auditing-code-reviewSkill
- security-headers-cspSkill
- settings-options-securitySkill
- shortcode-block-securitySkill
- user-data-protection-privacySkill
- woocommerce-securitySkill
- wp-cli-securitySkill
- wp-hardening-best-practicesSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 2 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 19
Use this skill for any custom SQL that includes a dynamic value:
- Very specific: line 25
Prefer the high-level APIs (WP_Query, get_posts, get_users, $wpdb->insert/update/ delete) when they fit — they parameterize for you.
- Distinctive: line 48
If raw SQL is needed, write the query with placeholders, not variables.
- Very specific: line 49
Call $wpdb->prepare( $sql, $args...
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL injection prevention with $wpdb
When to use this skill
Use this skill for any custom SQL that includes a dynamic value:
$wpdb->get_results(),get_var(),get_row(),get_col(),query().WHERE,IN (...),LIKE,LIMIT,ORDER BY, table/column names.- Custom tables, custom meta queries, reporting/analytics queries.
Prefer the high-level APIs (WP_Query, get_posts, get_users, $wpdb->insert/update/
delete) when they fit — they parameterize for you. Drop to raw SQL only when necessary,
and then always via $wpdb->prepare().
Core principles (and why they matter)
- Never concatenate user input into SQL. String interpolation is the root cause of
injection.
prepare()separates the query template from the data. - Use the right placeholder.
%d(integer),%f(float),%s(string),%i(identifier — table/column, WordPress 6.2+). The wrong placeholder can break quoting and reopen injection. prepare()quotes strings for you — don't add your own quotes. Writing'%s'(with surrounding quotes) double-quotes the value and breaks the query.esc_like()beforeprepare()forLIKE. Otherwise%and_in user input act as wildcards (and can be abused). Escape, then pass through%s.- Identifiers can't be parameterized as data. Column/table names and
ORDER BYdirection must be validated against an allowlist (or use%ifor identifiers in 6.2+). - Prefer the table prefix property:
$wpdb->prefix,$wpdb->posts, etc., never a hard-codedwp_.
Step-by-step implementation
- Can a core API do it (
WP_Query,$wpdb->insert)? If yes, use it. - If raw SQL is needed, write the query with placeholders, not variables.
- Call
$wpdb->prepare( $sql, $args... )and run the prepared string. - For
LIKE, wrap the term:'%' . $wpdb->esc_like( $term ) . '%', passed via%s. - For
IN()lists, build a placeholder string and spread the values. - For identifiers/sort columns, allowlist them (or use
%ion 6.2+).
Supporting references
| Reference | Load when |
| SQL injection prevention checklist | Before final verification of the sql injection prevention controls. |
| Secure wpdb query patterns | Implementing parameterized database query flows with typed values and safe identifiers. |
Common AI mistakes / anti-patterns
Mistake 1 — Interpolating input directly
// ❌ Insecure: classic SQL injection.
$id = $_GET['id'];
$row = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}orders WHERE id = $id" );// ✅ Secure: prepared statement with a typed placeholder.
$id = absint( $_GET['id'] ?? 0 );
$row = $wpdb->get_row(
$wpdb->prepare( "SELECT * FROM {$wpdb->prefix}orders WHERE id = %d", $id )
);Mistake 2 — Quoting the placeholder yourself
// ❌ Broken/insecure: prepare already quotes %s — this double-quotes.
$wpdb->prepare( "SELECT * FROM t WHERE name = '%s'", $name );// ✅ Correct: no surrounding quotes; prepare handles it.
$wpdb->prepare( "SELECT * FROM t WHERE name = %s", $name );Mistake 3 — LIKE without esc_like()
// ❌ Insecure: user-supplied % / _ become wildcards.
$wpdb->prepare( "SELECT * FROM t WHERE title LIKE %s", '%' . $term . '%' );// ✅ Secure: escape LIKE wildcards first, then prepare.
$like = '%' . $wpdb->esc_like( $term ) . '%';
$wpdb->prepare( "SELECT * FROM t WHERE title LIKE %s", $like );Mistake 4 — Building an IN() list by joining input
// ❌ Insecure: raw join of user values into IN().
$ids = implode( ',', $_POST['ids'] );
$wpdb->query( "DELETE FROM t WHERE id IN ($ids)" );// ✅ Secure: one placeholder per value, spread into prepare.
$ids = array_map( 'absint', (array) ( $_POST['ids'] ?? array() ) );
$ids = array_filter( $ids );
if ( $ids ) {
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
$wpdb->query(
$wpdb->prepare( "DELETE FROM {$wpdb->prefix}t WHERE id IN ($placeholders)", $ids )
);
}Mistake 5 — Dynamic ORDER BY / column name from input
// ❌ Insecure: identifiers can't be safely parameterized as %s.
$orderby = $_GET['orderby'];
$wpdb->get_results( "SELECT * FROM t ORDER BY $orderby" );// ✅ Secure: allowlist the column and direction, or use %i on WP 6.2+.
$orderby = sanitize_key( $_GET['orderby'] ?? 'created' );
$order = strtoupper( $_GET['order'] ?? 'DESC' );
$columns = array( 'created', 'name', 'total' );
$orderby = in_array( $orderby, $columns, true ) ? $orderby : 'created';
$order = ( 'ASC' === $order ) ? 'ASC' : 'DESC';
if ( version_compare( $GLOBALS['wp_version'], '6.2', '>=' ) ) {
$wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$wpdb->prefix}t ORDER BY %i $order", $orderby )
);
} else {
$wpdb->get_results( "SELECT * FROM {$wpdb->prefix}t ORDER BY {$orderby} {$order}" );
}Mistake 6 — Hand-rolled insert instead of $wpdb->insert()
// ❌ Insecure: manual INSERT with interpolation.
$wpdb->query( "INSERT INTO t (name) VALUES ('{$_POST['name']}')" );// ✅ Secure: $wpdb->insert() with format specifiers handles escaping.
$wpdb->insert(
$wpdb->prefix . 't',
array( 'name' => sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) ) ),
array( '%s' )
);Correct code examples
Full prepared-query patterns — single value, IN(), LIKE, insert/update/delete, and
allowlisted ORDER BY — are in
references/secure-wpdb-queries.php.
Checklist
- No user input is concatenated/interpolated into SQL.
- Every dynamic value goes through
$wpdb->prepare()with the right placeholder. %d/%f/%schosen by type; placeholders are not wrapped in extra quotes.LIKEterms are wrapped with$wpdb->esc_like()then passed via%s.IN()lists use one placeholder per value, spread intoprepare().- Identifiers /
ORDER BYcolumns are allowlisted (or use%ion WP 6.2+). - Table names use
$wpdb->prefix/$wpdb->posts, not hard-codedwp_. insert/update/deleteuse$wpdbhelpers with format specifiers where possible.
Official references
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

