WordPress Plugin Security: Preventing SQL Injection
SQL Injection is code injection on SQL queries used in an application using SQL database. WordPress uses MySQL so it has risks getting an attack through SQL Injection. In OWASP (Open Web Application Security Project) Injection is listed as the top threat in web-based applications, SQL Injection is a part of it.
We can prevent SQL Injection by utilising the wpdb functions provided by WordPress. Functions such as wpdb->insert(), wpdb->replace(), wpdb->update(), wpdb->delete(), wpdb->get_results(), etc. can be used to tamper data in database. If we can we should use these kind of functions which provided by the WordPress as they are quite safe.
However, sometimes we might still need to use some queries using the wpdb->query(). This can be risky if we do not properly escape the queries used. Luckily, WordPress already provided a function to help us prevent malicious queries, wpdb()->prepare.
Using wpdb()->prepare for the SQL query in wpdb->query() can prevent injection in WordPress. An example for this is:
\[code language="php"\] $wpdb->query( $wpdb->prepare(" INSERT INTO $wpdb->postmeta ( post\_id, meta\_key, meta\_value ) VALUES ( %d, %s, %s ) ", 101, "Sample meta", "Sample value" ) ); \[/code\]