0

Is this method of operation on the database is safe and correct?

 if(isset($_POST['name'])){

    $table = $wpdb->prefix.'_my_table';

    $post = trim(sanitize_user($_POST['name'], true));

    $part = $this->wpdb->prepare("WHERE name = %s", $post)

    $results = $this->wpdb->get_results("SELECT * FROM {$table} $part", ARRAY_A)

  }

2 Answers 2

1

What you're doing is safe.

However, some notes:

  1. See the WP_User_Query class in the Codex. This is the, "official," way to do something like this, although you'll get an integer-indexed array of WP_User objects. Instead of the ARRAY_A that you've specified.
  2. You probably don't want _my_table, unless your table is called something like wp__my_table (note the double underscore after wp). The prefix returned from $wpdb->prefix includes the underscore that many installations use after the prefix.
  3. The trim() call after sanitize_user() is superfluous. It doesn't hurt anything but it's also a waste of compute cycles.
  4. You may be able to write this in one line: $results = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}my_table where name = %s", sanitize_user($_POST['name'])), ARRAY_A); This may be better or worse for you.
1
  • Thanks for reply. I add acceptance to answer sent in the first place.
    – Jaron
    May 3, 2019 at 17:26
1

It's close. There's a few things that stand out.

First, I assume you're doing this before the code you shared. It's important to verify a nonce before accepting user input. Read more about Nonce in the Codex.

Next, you want to use sanitize_text_field in combination with wp_unslash. Trim is more of a helper function than for sanitizing, but it's helpful here to ensure expected results.

Finally, combine your entire SQL query in $wpdb->prepare(). Remember $wpdb->prefix usually includes an underscore. Your code would produce wp__my_table, for example (2 underscores).

Note: I changed $this->wpdb to the global $wpdb. This is probably unnecessary for you, but I wanted to make sure others that landed on this answer had the right context. I also changed the table name to posts and the name to title for testing.

if ( isset( $_POST['name'] ) ) {
    global $wpdb;
    $post_name = sanitize_text_field( wp_unslash( trim( $_POST['name'] ) ) ) );

    $sql = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}posts WHERE post_title = %s", $post_name );

    $results = $wpdb->get_results( $sql, ARRAY_A );
}

For more information on WordPress coding standards for sanitizing input data, check out The WordPress Coding Standards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.