0
0
Wordpressframework~5 mins

SQL injection prevention in Wordpress

Choose your learning style9 modes available
Introduction

SQL injection prevention helps keep your website safe by stopping bad people from changing your database with harmful commands.

When you accept user input like search terms or form data that goes into the database.
When you build custom database queries in WordPress plugins or themes.
When you want to protect login or registration forms from attacks.
When you handle data that affects your website content or user information.
When you want to keep your site secure and avoid data leaks or damage.
Syntax
Wordpress
$wpdb->prepare( $query, $value1, $value2, ... )
Use $wpdb->prepare() to safely insert user data into SQL queries.
It replaces placeholders like %s for strings and %d for numbers.
Examples
This safely adds the username into the query to find a user.
Wordpress
$wpdb->prepare( "SELECT * FROM wp_users WHERE user_login = %s", $username )
This safely adds a post ID number to get a specific post.
Wordpress
$wpdb->prepare( "SELECT * FROM wp_posts WHERE ID = %d", $post_id )
This safely checks comments by email and approved status.
Wordpress
$wpdb->prepare( "SELECT * FROM wp_comments WHERE comment_author_email = %s AND comment_approved = %d", $email, 1 )
Sample Program

This code safely gets a user from the database by username using $wpdb->prepare(). It stops SQL injection by escaping the username.

Wordpress
<?php
// Example: Safe query to get user info by username
global $wpdb;
$username = 'alice'; // Imagine this comes from user input

// Prepare the SQL query safely
$query = $wpdb->prepare( "SELECT * FROM wp_users WHERE user_login = %s", $username );

// Run the query
$user = $wpdb->get_row( $query );

// Show user info
if ( $user ) {
    echo "User ID: " . $user->ID . "\n";
    echo "User Login: " . $user->user_login . "\n";
} else {
    echo "User not found.\n";
}
?>
OutputSuccess
Important Notes

Never put user input directly into SQL queries without $wpdb->prepare().

Always use the right placeholder: %s for strings, %d for integers.

Using $wpdb->prepare() helps WordPress escape data safely to prevent attacks.

Summary

SQL injection prevention keeps your site safe from harmful database commands.

Use $wpdb->prepare() to safely add user data into SQL queries.

Always match placeholders to the data type to avoid errors and security risks.