【问题标题】:PHPMySQL query database with string / array problems with resultsPHP MySQL查询数据库与字符串/数组问题与结果
【发布时间】:2013-12-15 00:14:50
【问题描述】:

我是新手,所以如果我没有正确的短语,请耐心等待。 ;-)

我正在尝试查询数据库。我有一个可以有 1-3 个固定值的字符串,它来自一个复选框输入表单的内爆 $_Post["array"]。值类似于:

$string            // values (Berlin, New York, Rome) or (Berlin, Rome) ect.

现在我正在尝试查询一个数据库,其中每一行(项目)都有一个列(字段),其中有 1-3 个相同的值。

item1 (New York, Rome)
item2 (Berlin, New York, Rome)
item3 (Rome)

我尝试过这样的查询:

SELECT * FROM 'table' WHERE 'destination' LIKE '%$string%'
or
SELECT * FROM 'table' WHERE 'destination' IN '$string'

虽然理论上两者都有效,但它们并没有得到我想要的结果。这是我想从查询中得到的:

如果 $string 有所有 3 个值,我想显示 所有 3 个项目(不仅是 item2)。

如果 $string 有 value(Rome),我想显示 item1item2item3.

如果 $string 有 value(New York, Berlin) 我想显示 item1item2

任何想法如何实现这一目标?

非常感谢 赛博

【问题讨论】:

    标签: php mysql database string search


    【解决方案1】:

    假设您的意思是您的表列名称是目标,而 $string 是表单中的 post 值,您可以尝试 FIND_IN_SET:

    SELECT * FROM  `table` WHERE FIND_IN_SET($string,  `destination` );
    

    【讨论】:

      【解决方案2】:

      在这个例子中,我得到了带有列的table

      ID     destination
      1      New York, Rome
      2      Berlin, New York, Rome
      3      Rome
      

      还有一些来自 html 表单的输入 - 数组。 这有效:

      <?php
      $cities=array("Rome", "New York", "Berlin"); // simulation of form input
      
      foreach($cities as $value): // each city
        $result=mysql_query("SELECT * FROM `table` WHERE `destination` LIKE '%$value%'"); // find all match records for the city
        echo "<h3>For city \"$value\" I found in `table` these IDs</h3>";  
        while($value=mysql_fetch_array($result, MYSQL_NUM)): // fetch SELECT into rows
          echo "<pre>";
          print_r($value[0]); // prints IDs from DB corresponding with city in heading
          echo "</pre>";
        endwhile;  
      endforeach;
      ?> 
      

      【讨论】:

        【解决方案3】:

        好吧,伙计们!这是我最后所做的。谢谢你的帮助

        $query = "select * from table ";
        
        $query .= "WHERE
                    example1 like '$example1' 
                    AND example2 like '%$example2%' AND (";
        foreach($array as $Filtervalues)
        {
          $query .= " example3 like '%".$Filtervalues."%' OR";
        
        }   
        
        $query = trim($query, " OR"); 
        $query .= ")";
        
        $query .= " ORDER BY
                    name
                    "; 
        echo $query;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-12
          • 2019-03-21
          相关资源
          最近更新 更多