• I’m having a problem with a $wpdb query selecting results that contain single quotes.

    When a user visits a post, a $wpdb query searches the database for all other posts with the same title as the current one and then displays a link to them.

    This works fine for all post titles except those with a single quote in them. Other special characters work fine.

    A post with the title THE WEATHER: SUNNY will feature a list of all other posts with that title. But a post with the title TODAY’S WEATHER IS NICE will not find any other posts with that title even though several exist, just because it contains a single quote.

    I’ve searched for a solution but haven’t found one. Can anyone suggest a way around this?

    Here’s the code I’m using:

    global $wpdb;
    $itemName = get_the_title( $ID );
    $results =$wpdb->get_results("SELECT ID FROM $wpdb->posts where  $wpdb->posts.post_title LIKE '$itemName' AND $wpdb->posts.post_status = 'publish' ORDER BY post_title ASC", OBJECT);
    
    foreach ($results as $result){
    $newTitle =$wpdb->get_results("SELECT post_title FROM $wpdb->posts where  $wpdb->posts.ID = $result->ID", OBJECT);
    printf ($newTitle->post_title);
    }

    Someone on another forum suggested using wpdb->prepare but, at least with the way I’ve currently implemented it, it still returns the same results. I’d appreciate any suggestions.

Viewing 1 replies (of 1 total)
  • Leon Freeman

    (@leonfreeman)

    i’m glade you made this code working on some point, i’m also looking to solve pretty similar problem, can you describe me that your code above in your post goes where (eg: in “functions.php” or somewhere eles?).

Viewing 1 replies (of 1 total)
  • The topic ‘wpdb select doesn't work for searches containing single quotes’ is closed to new replies.