简体   繁体   中英

php How to search for keywords in mysql

I am using mysql database with php. I am a creating a photo gallery website in which I will be searching for images using their keywords. Keywords are already stored in the database separated by , I wanted to create a search field in which I will get a query like 'Merry Christmas'. I will be using implode function that will make these two keywords Merry and then the christmas. I wanted to search for these two words in the keywords field to search for the images that matches these results and return them in the order of maximum downloads. Downloads is also another column in database that has the information of total downloads. Basically I am new to SQL. Any help will be appreciated. Thanks in Advance.

Assuming the field name in your form is 'keywords', I think this is what you wanted to do more or less.

if (isset($_POST['keywords']) && $_POST['keywords']) {

    //explode with space
    $keywordList = explode(' ', $_POST['keywords']);

    //create OR clause for each keyword submitted
    $keywordClauseArr = array();
    foreach ($keywordList as $keyword) {
        $keywordClauseArr[] = "keywords LIKE '%$keyword%'";
    }

    //implode with OR
    $keywordClause = implode(' OR ', $keywordClauseArr);

    //finally create your sql string
    $sql = 'SELECT * FROM photos WHERE ' . $keywordClause . ' ORDER BY downloads DESC';

    //and then do your mysql query and other stuffs..

}

This will fetch the results with the keywords Merry or Christmas ordered by maximum downloads. Thanks.

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