sql LIKE查询只返回完全匹配,而不是类似的匹配

sql LIKE查询只返回完全匹配,而不是类似的匹配

问题描述:

I'm working on a $wpdb query to search for items in the media library. The search kind of works, except it only returns exact matches.

I have two images in the library, one called run and the other called running, if I search just run, it only returns the exact match, running isn't returned. Am I missing something here? I thought LIKE returned things that contains those characters?

Here's my query in full, I'm using AJAX to stick it into the page.

include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );

global $wpdb;

if( isset($_GET['nameLike']) ) {
    $search = $_GET['nameLike'];
} else {
    $search = '';
}

$results = $wpdb->get_results( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_status = 'inherit' AND post_title LIKE %s", $search), ARRAY_A);

foreach ($results as $result) : ?>

    <?php $image = wp_get_attachment_image( $result[ID], array(200, 150) ); ?>

    <div class="grid-1-4"><?php echo($image); ?></div>

<?php endforeach ?>

I wrote answer in the comment, I'll write here also how to implement it properly in WP. You can add '%' in your search term.

$results = $wpdb->get_results( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_status = 'inherit' AND post_title LIKE %s", '%' . like_escape($search) . '%'), ARRAY_A);

EDIT: Taken WP example from here