Struggling with PDO prepare and Wordpress

I am really struggling with PDO. I have looked at so many posts and tutorials on the web and am just getting more confused. (It was much easier to write plain mysql queries) :wink:

I currently have
[php]$studyname = $wpdb->get_row(“SELECT * FROM variants WHERE variant = ‘$surname’”);[/php]

This works perfectly and returns the results I expect.

But I need to sanitise $surname before I use it in the query.

So I have tried
[php]
$sql = “SELECT * FROM ‘variants’ WHERE variant = ‘$surname’”;
$result = $wpdb->prepare($sql);
$result->execute();
$studyname = $result->fetch(PDO::FETCH_ASSOC);
[/php]

and many variants and this just throws various errors. I am not sure whether this is me or Wordpress, I suspect me not understanding PDO.

Anyone got any suggestions?

[PHP]
$sql = “SELECT * FROM ‘variants’ WHERE variant = :surname”;
$result = $wpdb->prepare($sql);
$result->execute([
“:surname” => $surname
]);
$studyname = $result->fetch(PDO::FETCH_ASSOC);
[/PHP]

You may note the array is in [] rather than array(). This is because it is PHP 5.5.8 as opposed to lower versions of PHP which handles arrays differently.

Thanks for this but unfortunately I get the White Screen of Death with this query. This is one of the problems I have been having.

My php version is 5.3.28 so I expect your syntax won’t work for me.

Ignore this. :-[

I have done some more reading and you don’t use conventional PDO with Wordpress it has its own functions built in.

To sanitise data is easy you just use

[php] $variable = sanitize_text_field(variable);[/php]

There are several other sanitise functions built in.

Sorry to waste everyone’s time.

Sponsor our Newsletter | Privacy Policy | Terms of Service