简体   繁体   中英

why does this search of a mysql database produce no results? Using LIKE for the first time

Editing someone else's code here, so I can't change the field in the database called title or change to MySQLi etc :/

The code connects to the DB without problems, but always pulls in zero results.

$strSQL = "SELECT * FROM newproducts WHERE 'title' LIKE ('%$q%')";
$sql = mysql_query($strSQL) or die(mysql_error());
$num_rows = mysql_num_rows($sql);

if ( $q == '' ) {
    echo '<p class="black-text">Please provide a search term.</p>';
}

else if ( $num_rows <= 0 ) {
    echo '<p class="black-text">Your search for <b>'.$q.'</b> returned <b>0</b> results.</p>';
}

else { 

    echo '<p class="black-text">Your search for <b>'.$q.'</b> returned <b>'.$num_rows.'</b> result(s).<br/><br/>';  
    while($row = mysql_fetch_assoc($sql)) {
        echo '- '.$row['title'].' <a href="'.$row['link'].'.html" class="search-link">[Read more]</a><br/>';
    }
    echo '</p>';
}

Could it be a case issue? I've tried searching for lower and upper strings, but still zero results.

In MySQL single quotes denote strings:

SELECT * FROM newproducts WHERE 'title' LIKE ('%$q%')

Should be

SELECT * FROM newproducts WHERE title LIKE ('%$q%')

Additionally, you are testing for if ($q == '') after you have performed the query - you may want to do that before - but that isn't causing your issue.

And lastly, you are at risk of SQL injection by using potentially unsafe user input - but I'm not going to delve into that as it isn't directly related to your question. Most PHP developers are using prepared statements these days to make their queries safer (and because the old style of running queries is going to be deprecated).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM