dongpang2029 2014-11-11 11:05
浏览 198
已采纳

是否有一个SQL函数循环遍历数组以查看是否有任何元素在MYSQL行中?

I have a small SQL table. There is a 'tags' column that has several words separated by a comma. Using PHP & MYSQLI I would like to take a Search Value and compare it's individual words with the individual words in the tag SQL 'tags' column.

It is a relatively small database. I can think of a way to do this where I create a seperate column for every tag. But I would rather not. Only if that is the only option.

Example SQL layout, Table: Books

"title" -- "author" -- "tags"

[Potter]-- [J.K.] -- [Wizards, WandsnShit,Magic]

[50 shades]-- [James] -- [Boobies, Sex]

[Ulysses]-- [Joyce] -- [WTF]

So far my direction has been:

//obtains searchValue from HTML
$searchValue=$_GET["searchValue"];

//turns the values individual words into an array
$proxy = $searchValue;
$tags = explode(" ", $proxy);

//This is where I need help
SELECT * FROM books WHERE tags CONTAINS (cycle through 'tags' array)

If all works correctly, typing "Gandalf is a wizard" should return the book "Potter". Because "Wizard" is a tag of "Potter" book.

Also while I'm at it. Does the PHP function "explode" alter the original string or create a copy string an alter that?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dsajkdadsa14222 2014-11-11 11:16
    关注

    This is a bad design. Let's search on the net for database normalization.

    In your book table should be a unique id (primary key, int, not null, auto increment) field. After that, you need to create a relation table, what has the tags.

    For example:

    Book table:

    id
    name
    author
    

    Tags table

    id
    book_id
    tag
    

    After that you can use:

    $sql = "SELECT * FROM books"
        . " INNER JOIN tags ON tags.book_id = books.id"
        . " WHERE tags.tag = " . mysqli_real_escape_string($_GET["searchValue"]);
    

    Or you can use LIKE keyword.

    Note:

    I am always wondering, why a lot of developer create 2 variable for nothing?

    $searchValue=$_GET["searchValue"];
    //turns the values individual words into an array
    $proxy = $searchValue;
    $tags = explode(" ", $proxy);
    

    instead: $tags = explode(" ", $_GET["searchValue");

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号