MySQL query not working when a variable is used Inside the query

I’ve encountered a strange issue where my MySQL query works for all cases except for one particular data entry.

Here’s my query:

Read More
SELECT * FROM wp_songs WHERE album_name = '{$current_album}'

This query is fed into the WordPress $wpdb->get_results() function. For some reason it can never find this particular data entry: “Raw & Uncut: The Mixtape”

However, if the query is instead changed to:

 SELECT * FROM wp_songs WHERE album_name = 'Raw & Uncut: The Mixtape'

The data is found without a problem.

Running the $wpdb->last_query function returns the exact same line in both cases.

The issue is only for one data entry. I have not been able to replicate the problem with other data entries. All other entries work with my original query.

More code:

This does not work:

 $current_album = "Raw & Uncut: The Mixtape";
 $songs = $wpdb->get_results("SELECT * FROM wp_songs WHERE album_name = '{$current_album}'")
if ( $songs ) { echo "Works"; }

This works:

  $songs = $wpdb->get_results("SELECT * FROM wp_songs WHERE album_name = 'Raw & Uncut: The Mixtape'");
  if ( $songs ) { echo "Works"; }

Again, it’s only for that specific data entry. Every other entry works with both queries.

Running var_dump($current_album) returns:

string(28) "Raw & Uncut: The Mixtape"

Related posts

Leave a Reply

1 comment

  1. You posted the results of var_dumping $current album:

    string(28) “Raw & Uncut: The Mixtape”

    “Raw & Uncut: The Mixtape” is only 24 characters – what that tells me is that your variable actually contains this:

    Raw & Uncut: The Mixtape

    Which doesn’t match what you have in the database. You can correct it by running html_entity_decode() on your album variable.