$wpdb returns no results with SELECT query on custom post type, works on default post type

I’ve solved the problem myself though it is probably not be the right way to do it. Note that I’ve had to type “website-address” instead of the actual URL because system here won’t let me use more than one URL in a post without more reputation. That makes it quite difficult to convey what’s actually going on of course, but there is no choice for that it seems. In the actual code and in the table, the actual URL is there.

The issue is that when trying to select a record from the table where the qrci_guid is a url like “http://testsite.com/?post_type=quilt&p=213” it seems to hang up on the ampersand. In the beginning, the $post->guid was being inserted into the custom table like this:

website-address/?post_type=quilt&p=213

but returns this error when trying to retrieve the data:

WordPress database error: [] SELECT * FROM wp_customtable WHERE qrci_guid = “website-address/?post_type=quilt&p=213”

The select statement is looking for & and the record contains &. I tried stripping the ampersand out of the guid before inserting into the table and stripping the ampersand out of the $post->guid before building the query, but that didn’t work to get the record either. That resulted in this in the table:

website-address/?post_type=quiltp=239 

which was fine, because I don’t really need the ampersand in there anyway for my purposes, but the error looked like this:

WordPress database error: [] SELECT * FROM wp_customtable WHERE qrci_guid = “website-address/?post_type=quiltamp;p=239”

so still no record returned.

In the end, I solved this by using this code before inserting the $post->guid into the table:

$clean_guid = str_replace("&", "amp;", $post->guid);

and inserting the $clean_guid instead of the $post->guid, and then using this code before querying the table:

$clean_guid = str_replace("&", "", $post->guid);

and then using this query to retrieve the data:

$sql="SELECT * FROM " . $wpdb->base_prefix . 'customtable WHERE qrci_guid = "'. $clean_guid . '"';
$query = $wpdb->get_row($sql);

which returned the row as expected.

As I said, this is probably not the right way to do this; I know there are PHP functions like htmlentities() and urlencode() and other such functions, one of which might have been the right one to use in this situation, and I even used to know how to use all of those functions effectively three or four years ago when I was doing a lot of PHP coding. My coding experience is rusty obviously and I couldn’t make any of those other functions work, but this solution worked for me. If there’s a better way, I’d be glad to hear it.