Support » Developing with WordPress » $wpdb queries no longer work when using multiple % characters – PHP 8.0 issue?

  • Resolved fijisunshine

    (@fijisunshine)


    Recently, some $wpdb queries have stopped working properly in functions.php. I think the reason might be that I upgraded from PHP 7.4 to PHP 8.

    $wpdb->get_var($wpdb->prepare(‘SELECT COUNT(*) id FROM custom_table WHERE field1 LIKE “%s%”‘, $prepare))

    The query always returns 0 but it shouldn’t. The issue is the “%s%”. If I change that to “%s” then the query works. But I need the wildcard character %. $wpdb seems to no longer like more than one % in the quote.

    A similar query also always returns 0 now. But it shouldn’t. Again the issue is the multiple % in the quote:

    $wpdb->get_var($wpdb->prepare(‘SELECT COUNT(*) id FROM custom_table WHERE field1 LIKE “%s%s”‘, $prepare2))

    Any suggestions? Thank you

Viewing 4 replies - 1 through 4 (of 4 total)
  • Hi @fijisunshine,
    Have you tried passing the wildcard character in the replacement argument like this:
    LIKE ā€œ%sā€ā€˜, $prepare . '%')

    Thread Starter fijisunshine

    (@fijisunshine)

    Hi @eltobiano,

    Thank you for your response. For simplicity purposes, I had simplified my queries for you but $prepare is actually an array with multiple strings, i.e. my query actually has AND statements and multiple %s.

    Would it be possible to use your suggestion given than $prepare is an array? If not, any other suggestions?

    Thanks again

    Thread Starter fijisunshine

    (@fijisunshine)

    Update:

    When running the sql query, $wpdb is putting single quotes around the content of each %s. For example, “%s%” is being run as ‘%s’% in the query. But it should be run as ‘%s%’. This is the issue.

    Based on @eltobiano’s helpful suggestion, I added .’%’ to the appropriate string in the array called $prepare. Therefore, the % is now included within the %s and the query runs correctly.

    So my issue is “resolved”. But I think it’s a dangerous issue for others because many sql queries that appear to be correctly written, and previously worked properly, will now only return 0.

    I’m not sure if this is due to PHP 8.0 or recent updates to the WordPress core.

    Thanks again

    Thread Starter fijisunshine

    (@fijisunshine)

    Marking as resolved.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.