How to Clean Malware From a Hacked Database


Every day, thousands of website databases around the world are targeted by hackers looking to steal, destroy, or alter website data and content. A hacked database can have severe repercussions for a website, including loss of sensitive customer information, damage to reputation, and even legal consequences. 

A database hack occurs when an unauthorized individual gains access to your database environment, often by exploiting vulnerabilities in your website or server. Once inside, they can inject malicious code, alter your data, or even lock you out of your own website. 

This guide aims to educate website owners about how to detect and clean malware and spam from a hacked database, as well as how to secure it against future threats.

Why should I care about malware in the database?

When a user visits a page on your site, the CMS combines content stored in your database with the logic in the CMS’s source code to display the page.

If your website database becomes compromised, it can directly impact your website’s functionality — even if you replace the CMS’s source code with a fresh copy. 

So, in the aftermath of a hack, it’s vital not only to identify but also permanently remove any malware present in the database. Thoroughly cleaning your database is a critical step towards recovering from a security breach, ensuring your website operates as intended, and safeguarding your site’s overall security.

How do website databases get hacked?

Understanding how a database becomes compromised is the first step in preventing future attacks. Here are some of the most common ways a hacker can gain unauthorized access to a website’s database.

SQL injection

This technique is one of the most prevalent methods of hacking a database. SQL (Structured Query Language) is the language that is used to communicate with and manipulate databases. SQL injections occur when a hacker inserts malicious SQL code into a query.

Often, this is done through website forms or URL parameters. For instance, if you have a form on your website that asks for a user’s email address, a hacker might input SQL statements instead of a legitimate email address. If your website is not properly secured, these statements can be run against your database, leading to unauthorized access or data manipulation. From a CMS perspective, improper input sanitization in themes, plugins or extensions may lead to SQL injection, giving attackers a direct hold over the CMS database.

Website malware

Malware, short for malicious software, is a broad term that encompasses various types of harmful software, including viruses, trojans, ransomware, and spyware. Hackers often use malware to gain unauthorized access to a database, steal data, or disrupt database operations.

The process usually starts with the hacker finding a way to deliver the malware to your website or server. This could be through a malicious email attachment, a compromised download, or an infected website that your server interacts with. Although endpoint devices are not among the top causes of website infection they are still part of the attack surface for website administrators.

Once the malware is on your website or server, it can perform a variety of malicious tasks. Some malware is designed to search for and exploit vulnerabilities in your database software, giving the hacker access to your data. Other types might create a backdoor, allowing the hacker to come and go as they please.

Unpatched vulnerabilities

If your website or server software is out of date, it may have known vulnerabilities that hackers can exploit.

These security holes or vulnerabilities can occur in any part of your system – your website’s content management system (CMS), plugins or extensions you’re using, your server’s operating system, or even the database software itself.

Here’s an example: suppose you’re running an outdated version of a CMS like WordPress. A vulnerability in this older version might allow a hacker to upload and execute a malicious script on your server. Once this script is running, it could then be used to access or manipulate your database.

Hackers are always on the lookout for systems running outdated software, and they often use automated tools to find and exploit these vulnerabilities. If a vulnerability is well-known and your software is unpatched, it’s not a matter of if your database will be hacked, but when.

Weak or stolen credentials

If your database username and password are easy to guess, or if they have been stolen, they can be used to gain direct access to your database.

There are several ways weak or stolen credentials can lead to a hacked database:

  • Brute Force Attacks: In this type of attack, hackers use software tools to try thousands (sometimes millions) of different username and password combinations until they find one that works. If your database credentials are weak (such as using ‘password’ or ‘12345’ as your password), a brute force attack can crack them in no time.
  • Phishing Attacks: In a phishing attack, a hacker tricks someone into revealing their username and password. This could be through a fake login page that looks like a legitimate service you use. If one of your team members falls for a phishing attack and enters their database username or password, those credentials are now in the hands of the attacker.
  • Data Breaches: If you or one of your team members uses the same username and password for multiple services and one of those other services suffers a data breach, your database could be at risk. Hackers often try stolen credentials on multiple services, hoping that people have reused passwords.
  • Remote MySQL administration: Although this is disabled by default in a cPanel installation, the option does exist to open up remote administration of the database. This allows external / third party IP addresses to access the database. If this is open to the world it allows attackers to brute force the database connection strings in order to obtain access.

Each of these methods relies on a different type of vulnerability in your database, whether it’s in the software you’re using, your website code, or your own security practices.

Anatomy of a database hack

Here’s a simplified breakdown of how a typical website database hack might occur:

Anatomy of a Database Hack Sucuri Guides How to remove Malware from a Hacked Database

Let’s take a quick look at the steps illustrated in the diagram. 

  1. Reconnaissance: This is the initial phase where hackers identify potential targets and gather information about them. They might use automated tools to scan the internet for websites running outdated software or plugins with known vulnerabilities.
  2. Exploitation: Once a target is identified, the hacker will move to exploit the known vulnerability. This could involve using SQL injection, uploading and executing a malicious script, or taking advantage of weak or stolen credentials to gain unauthorized access. What the attacker does is contingent upon what the vulnerability they exploit allows them to do.
  3. Establishing persistence: After gaining access, hackers often create a way to maintain access, even if the initial vulnerability is patched. This could involve installing a web shell for remote access or creating new admin user accounts within your system.
  4. Data access and manipulation: With access secured, the hacker can now interact with your database. They could steal data, alter existing data, or even delete data. Sometimes, the goal isn’t data theft but disruption of services.
  5. Covering tracks: A sophisticated hacker will often attempt to hide their activity to avoid detection. They might delete logs, alter timestamps, or use other techniques to make it appear as if they were never there.

Understanding this process can help you secure your database at each stage. For instance, regular security audits can help detect reconnaissance activity, up-to-date software can prevent exploitation, and monitoring user activity can help detect unauthorized access.

Steps to clean a hacked website database

Cleaning a hacked database can seem intimidating, but by following a systematic process, you can remove the malware, restore your site’s functionality, and harden it against future attacks.

Step 1: Log into your database admin panel

The first step in the cleanup process is to log into your database administration panel. This could be a web-based interface like phpMyAdmin (accessed through cPanel), a tool such as Adminer, or a software application like MySQL Workbench, depending on your hosting environment.

PHPMyAdmin Login Screenshot sucuri guides how to remove malware from hacked database
Users overview in PHPMyAdmin (Source: phpMyAdmin)

This panel gives you direct access to your database and allows you to run SQL queries, view and modify database tables, and perform other administrative tasks. You’ll need this access to search for and remove malicious content in your database.

To log in, you’ll need your database username and password. If you don’t have this information, you can typically find it in your website’s configuration file (like ‘wp-config.php‘ for WordPress sites) or get it from your hosting provider.

Once you’ve logged in, you can navigate to the section where you can manage your databases (in cPanel, this would be under the ‘Databases‘ section). From there, select the database that you suspect has been hacked.

Remember to proceed with caution. The database admin panel lets you directly interact with your database, which means you could accidentally alter or delete important data. Always make sure you have a backup before making any changes (see step 2).

Step 2: Make a backup of your website and database

Backing up your website and database is a critical step before making any changes to your website or trying to clean up a hack. A backup serves as a safety net, allowing you to restore your site to its current state if something goes wrong during the cleanup process.

Steps to Backup a Website & database sucuri guides how to remove malware from a hacked database

1 – Backup your website files
Start by backing up all your website’s files. This includes all scripts, images, plugins, themes, and configurations. 

If you’re using a hosting control panel like cPanel, there’s usually an option to backup all the files in your home directory. Alternatively, you can use an FTP client like FileZilla to manually download all your site’s files to your local machine.

2 – Backup your database
Next, you need to create a backup of your database. In your database management tool (like phpMyAdmin or MySQL Workbench), there should be an option to “Export” your database. This will create a .sql file that contains all the data in your database and the commands to recreate it. Save this file to a secure location. 


If the infection is in a particular database table you may want to also make an additional backup of that specific table as it will make the restore process much easier if something goes wrong during the remediation process.

3 – Verify that your backups actually work 
After creating the backups, verify them to ensure they’re not corrupted and that they contain all necessary data. Try opening the .sql file with a text editor to ensure it’s not empty, and consider restoring it on a local test environment to confirm it works as expected.


4 – Safely store your backups offsite
Store your backups in a safe and secure location. This could be a secure cloud storage service or an external hard drive — just don’t keep them on the same server as your website. Make sure wherever you choose is secure and not easily accessible to potential hackers.

Remember that backups should be a routine part of your website maintenance, not just something you do when facing a security issue. Regular backups help mitigate the damage of potential future hacks, allowing you to restore your site quickly and easily.

Step 3: Check database tables for suspicious keywords and links

After you’ve backed up your website and database, the next step is to begin the investigative process. Hackers often leave traces in your database tables in the form of suspicious keywords, links, or scripts.

To perform this step, you’ll need to use a tool that allows you to run SQL queries on your database. This could be a web-based tool like phpMyAdmin, a part of your web hosting control panel, or a standalone application like MySQL Workbench.

Here are the steps you can take to check your tables.

1 - Identify what to look for

Start by identifying what you are actually looking for. Manually checking database tables and columns one by one is a fool’s errand so you’ll need to know what to search for. 

Start by running your website through our Sucuri SiteCheck tool – it should flag any known malware or spam lodged in the website, and oftentimes this will be lodged within the database (especially for spam and Balada malware). If you are noticing your website redirect to third party websites or see any other strange behavior or content, take note of what they are so you can search for those particular strings.

Database tables which are most commonly affected by malware and spam in a WordPress environment are as follows:

  • wp_posts
  • wp_options
  • wp_postmeta
  • wp_users

While on Magento environments our teams most commonly find credit card skimmers in the core_config_data table, but also tables such as cms_block, cms_page and variable_value.

You’ll want to take note of your database prefix as well. WordPress databases commonly use wp_ as the prefix, but some sites may use other unique variations.

3.2 Change user passwords to prevent reinfection

SQL (Structured Query Language) is a language used to manage and manipulate databases. Database management tools like PHPMyAdmin and Adminer have built-in search functions which allow you to easily search for strings lodged in the database. You can also use SQL queries with regular expressions to search for specific patterns in your database that indicate the presence of malicious content. 

For instance, you could search for links to known malicious websites, SEO spam keywords, or even query for common malware scripts.

Here’s a sample query for this scenario that you can customize for your environment:

SELECT * FROM your_table WHERE your_column REGEXP 'suspicious_pattern';

This uses the REGEXP command to search for items matching a specific pattern, but you can also just use the basic search function if you’re not familiar with crafting regular expressions.

Let’s provide another example to elaborate further on the query. Imagine you happen to be searching for gambling spam keywords in your WordPress posts. 

The query would then look like this:

SELECT * FROM `wp_posts` WHERE `post_content` LIKE '%gambling%';

And if you were looking for gambling keywords in your WordPress website’s post titles, you might use the following command instead:

SELECT * FROM `wp_posts` WHERE `post_title` LIKE '%gambling%';

You can find an extensive list of common WordPress database tables in the WordPress Codex

Certain keywords may indicate the presence of malware. These could be terms related to hacking, pharmaceuticals, gambling, or any other keywords that seem out of context for your website. 

Remember, false positives are possible when searching for suspicious content. Be careful not to mistakenly flag or delete legitimate content. When in doubt, investigate further before making any changes.

3 - Check for suspicious links

You will also want to check your database for any links that seem out of place or lead to unfamiliar websites. Hackers often inject their own URLs into a website’s database to redirect traffic, host phishing pages, or spread malware.

According to our latest hacked website report, 53.75% of all infected databases were found to contain SEO spam, the majority of which were hidden links. Another 11.15% of infected databases were found to contain injected scripts from known malicious domains.

In 2022 these five domains were found injected into 7.6% of all infected databases, all of which are related to the massive Balada Injector campaign:

  • storerightdesicion[.]com
  • legendarytable[.]com
  • classicpartnerships[.]com
  • weatherplllatform[.]com
  • specialadves[.]com

Step 4: Check comments meta for spam

Comment spam has plagued WordPress websites for many years. Although it’s not usually explicitly harmful it can be a major nuisance for websites which have comments enabled. Automated bots will pollute WordPress websites with spam links to pharmaceutical knockoffs, essay writing services, and bootleg designer wear. If publicly viewable these spam comments can harm your site’s SEO and alienate genuine users. To prevent comment spam from getting onto your website in the first place consider using an anti-spam plugin.

Of course, you can always just use the wp-admin interface for searching for and removing spam comments, but it can be done directly in the database as well. That also might be a bit more effective and efficient if you are dealing with many thousands of them.

Here’s how to check your comments meta for spam directly in the database:

1 - Identify the comments table

Start by identifying the database table that stores your website’s comments. In WordPress, for instance, this is typically the “wp_comments” table and the related “wp_commentmeta” table.

2 - Use SQL queries to check for spam

Much like you did when checking for suspicious content, you can use SQL queries to search through your comments as well. Look for comments with suspicious or out-of-place content, such as links to irrelevant or shady websites, comments written in poor or nonsensical English, or comments that seem overly promotional.

An example SQL query to search for gambling spam might look like this:

SELECT * FROM wp_comments WHERE comment_content LIKE '%gambling%';

3 - Check the comment author meta

Spammers often use a fake or suspicious name, email, or URL when posting their comments. Check the comment_author, comment_author_email, and comment_author_url fields in your comments table for any suspicious entries.

Step 5: Check for malicious PHP functions

PHP is a scripting language widely used in web development, including in content management systems like WordPress. While PHP functions are essential for your website to work correctly, some functions are often misused in hacking attempts.

These malicious functions can be used to execute arbitrary code, obfuscate malicious activity, or create backdoors for persistent access. 

Some commonly misused functions include: 

  • eval()
  • base64_decode()
  • gzinflate()
  • preg_replace()
  • str_replace()

Here’s how to check for these PHP functions in your database:

1 – Identify tables containing PHP code

Although it’s not overwhelmingly common, sometimes PHP code can be injected into tables related to your website’s theme or plugin settings, options, or any custom tables that might store executable code.

2 – Use SQL queries to search for malicious functions

Much like you did when checking for suspicious content, you can use SQL queries to search for these functions. 

For example:

SELECT * FROM db_table WHERE db_column LIKE '%eval\\(%';

This query will return all records in ‘your_table’ where ‘your_column’ contains the string ‘eval(‘.

3 –  Investigate potential threats

If your query returns any results, investigate these thoroughly. Remember that these functions have legitimate uses, so their presence doesn’t necessarily mean your site has been hacked. Look for suspicious patterns, such as long, obfuscated strings of code, or functions being used in places where you wouldn’t expect.

Step 6: Remove malicious code, URLs & spam

As soon as you’ve identified and confirmed the presence of any suspicious links, malicious code, unwanted keywords, or spam comments, you can delete them from your database. Be sure to also delete any related entries in the commentmeta table to keep your database clean and organized.

You can use either SQL DELETE or UPDATE commands to delete rows or update specific fields in your database. 

Here’s an example query that will fully remove spam comments containing the string “gambling”:

DELETE FROM `wp_comments` WHERE `comment_content` LIKE '%gambling%';

Be aware that this specific command will fully remove the database content that contains that string, so you would only want to use this for the wp_comments table. Using this command to remove a JavaScript injection in wp_posts, for example, will fully remove the posts and quite likely remove legitimate content from your website.


Both posts and pages are stored in wp_posts, so act accordingly!

Here’s an example command that will find a specified string in the database and replace it with content of your choosing (for the purposes of malware removal, you’d normally want to replace it with empty content):

UPDATE wp_posts SET post_content = REPLACE ( post_content, 'text to find here', 'text to replace here');

These queries need to be properly escaped lest the command get truncated. So any instance of an apostrophe ‘ will need to be preceded by a backslash \ and some other special characters will require escaping as well.

Let’s say we wanted to remove this (fictitious) JavaScript injection from wp_posts:

					<script src='' type='text/javascript'></script>

We would run the following SQL query to get rid of that and replace it with empty content, thereby cleansing the injection from the database:

UPDATE wp_posts SET post_content = REPLACE ( post_content, '<script src=\'\' type=\'text/javascript\'></script>', '');

Notice how the apostrophes all have a backslash before them. The reason for this is that the MySQL syntax itself uses apostrophes, so without escaping them (with backslashes) it would prematurely terminate the query and result in a syntax error. Placing the backslash before it causes MySQL to treat it as a normal character, rather than as part of the query.

Remember, manual code removal can be risky and might not fully clean your website if the malicious code has spread or if there are multiple variants present in your environment. For example, sometimes content in the database is serialized, particularly in wp_options. Removing this outright can damage your website, as doing so will break the serialization. For such cases, it is safer to remove the malicious content directly from your wp-admin or other CMS administration panel.

An example of serialized database content might look something like this:


Furthermore, deleting the symptom will not address the root cause of the issue. For that, you’ll need to identify and fix the original reason your database was compromised in the first place. 

In short, always keep a backup and consider seeking professional help if you’re unsure.

Protect Your Website & Database from Malware

The Sucuri Web Application Firewall (WAF) and Intrusion Prevention System (IPS) prevents hacks and protects your website from hackers, brute force attacks, bad bots, DDoS, and malware.

Securing your database after a hack

After cleaning malware or spam from a hacked database, it’s crucial to take steps to secure it against future attacks. This will help protect your website from hackers and reduce the risk of another breach. Here are a handful of best practices for database security.

1 – Regularly patch and update your software

Always keep your CMS, plugins, themes, and server software up-to-date. This is one of the most effective (and simple) ways to protect your website and database. Software updates often include patches for known security vulnerabilities; by not patching your software with bug and security fixes, you leave your website exposed to known vulnerabilities.

2 – Always use strong and unique passwords

Use strong and unique passwords for all your accounts — especially for your database and hosting credentials. Strong passwords are long (at least 12 characters), include a mix of uppercase and lowercase letters, numbers, and special characters, and are not easily guessable. In the wake of a website compromise it’s important to change all passwords including the database password.

3 – Enable Two-Factor Authentication (2FA)

Always enable 2FA for all your accounts whenever available. This adds an extra layer of security by requiring a second factor (like a code sent to your phone) to log in, in addition to your password and can help deter brute force attacks.

4 – Maintain regular database backups

Regularly back up your website and database. If your site is hacked, a recent backup can help you restore your site quickly and minimize downtime.

5 – Limit database access

Limit who has access to your website database. The fewer people who have access, the smaller the attack surface area and less likely the credentials could be lost, phished, or harvested. Always ensure that remote database administration is disabled in your cPanel settings unless your website explicitly requires it.

6 – Monitor your website and database

Regularly check your website for signs of hacking, including sudden drops in traffic, an unexpected change in your site’s appearance or functionality, or warnings from your web browser or Google Search Console.

7 – Use a Web Application Firewall (WAF)

A web application firewall can help protect your website by filtering out malicious traffic, blocking known malicious IPs, and stopping common hacking attempts like SQL injection or cross-site scripting (XSS) attacks.

Need help fixing a hacked database?

Sucuri Resource Library

Say on top emerging website security threats with our helpful guides, email, courses, and blog content.


Learn how to identify issues if you suspect your WordPress site has been hacked.

Email Course

Join our email series as we offer actionable steps and basic security techniques for WordPress site owners.


Based on our data, the three most commonly infected CMS platforms were WordPress, Joomla! and Magento.