简体   繁体   English

php如何在mysql中搜索关键字

[英]php How to search for keywords in mysql

I am using mysql database with php. 我正在使用php的mysql数据库。 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'. 关键字已经存储在以分隔的数据库中,我想创建一个搜索字段,在该字段中将得到类似“ Merry Christmas”的查询。 I will be using implode function that will make these two keywords Merry and then the christmas. 我将使用爆破功能,使这两个关键字成为Merry,然后成为圣诞节。 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. 基本上,我是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. 这将以最大下载量排序的关键字Merry或Christmas来获取结果。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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