Should I use wpdb prepare?

The question:

I’m new to SQL and am wondering if I need to use wpdb->prepare for the following query to a table I’ve created

global $wpdb;
$tablename = $wpdb->prefix . "my_custom_table";
$sql = "SELECT * FROM " . $tablename . " ORDER BY date_created DESC";
$resulst = $wpdb->get_results( $sql , ARRAY_A );

Do I need to use prepare here? How would I do that?


The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

It’s best practice to always use prepare but the main use of it is to prevent against SQL injection attacks, and since there is no input from the users/visitors or they can’t effect the query then that is not an issue in your current example.

But like I said before it’s best practice to use it and once you start using it you never stop, so in your example you can use it like so:

global $wpdb;
$tablename = $wpdb->prefix . "my_custom_table";
$sql = $wpdb->prepare( "SELECT * FROM %s ORDER BY date_created DESC",$tablename );
$results = $wpdb->get_results( $sql , ARRAY_A );

to read more about how to use it head to the codex

Method 2

When you use prepare it is protecting the code from SQL injection vulnerabilities.

Here is the code you need to modify for using prepare();

global $wpdb;
$tablename = $wpdb->prefix . "my_custom_table";
$sql = $wpdb->prepare( "SELECT * FROM {$tablename} ORDER BY date_created DESC");
$resulst = $wpdb->get_results( $sql , ARRAY_A );

Method 3

In your case is not possible SQL injection attack. Your code don’t need additional protection because don’t use user input like: post, get, request, cookie.

Don’t use complicated function when are not necessary to save server resources.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment