0

My 1st post. :) Is there a function similar to bindParam in wpdb? Kind of like this (theoretical) setup?:

$names = text, array, object...whatever

$sql = "SELECT spouse FROM people_table WHERE person_name LIKE :names ";

$wpdb->prepare($sql);

$wpdb->bind(:names, $names); //this is the concept I'd like

$results = $wpdb->get_results($sql); 

return $results;

I just spent more hours than I care to admit trying to get %LIKE% to work on a SQL stmt in wpdb. I'm creating a plugin using Namespaces and Classes. I was almost certain that was screwing me up, but it turns out there's just really AWFUL, outdated info online. EVERY solution I found failed...except for one, by my new hero Sneha Agarwai here on the wp stackexchange site. I'm using his solution (which was not at all obvious to me). I'll post my version of his solution here just in case it helps anyone else. BUT...since WP keeps changing, I have a feeling this solution will be outdated in a year or two. I cannot understand why there isn't a more clear, concise solution. And I REALLY can't understand why the WP codex has incorrect solutions on their site. But anyway...here's the code. Maybe it'll help someone else.

 public function find_prefixed_dbmodulenames($strPrefix){
        global $wpdb;
            $like = "%" . $wpdb->esc_like(stripslashes($strPrefix))."%"; 
            //escape this for use in LIKE statement
        $sql = "SELECT * 
        FROM $wpdb->options 
        WHERE option_name LIKE %s
        ";
        $sql = $wpdb->prepare($sql,$like);
        $results = $wpdb->get_results($sql);
        return $results;
    }

That $like stmt works (and I'm super grateful I found it), but it's baffling and seemingly overly complicated.

(And, yes...I realize I should sanitize the input to be safe. I'm not done yet, so any suggestions on improvement are welcome.)

So, back to my original question: Is there a smarter/concise/intuitive solution more similar to bindParam PDO?

2
  • Did you see this one? Didn't help you? wordpress.stackexchange.com/a/8847/122788 Commented May 9, 2018 at 12:29
  • I DID! And I tried to implement it, but it didn't work for me. That's the thing...there's conflicting info online. Another post I read said backticks no longer worked in wpdb sql statements. Plus, this line seemed odd to me "{$wpdb->base_prefix}my_table" it's backticked AND there was a smarter solution available for my particular situation. For me, it was: "SELECT * FROM $wpdb->options WHERE..."
    – Michael D
    Commented May 9, 2018 at 12:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.