0

所以我有一个附有多个类别的项目表。我一直遇到问题。这是我的代码片段:

    <form class="forms" action="form.php" method="get">
    <fieldset>
    <legend>Sort by Category</legend>
    <select name="tags">
    <option value="business" title="Business">Business</option>
    <option value="environmental" title="Environmental">Environmental</option>
    <option value="hospitality" title="Hospitality">Hospitality</option>
    </select><input type="submit" class="inputButton" value="Select Category" />
    </fieldset>
    </form>

    <?php
    $tags = $_GET['tags'];


    $connection = mysql_connect($local,$user,$pass) or die (mysql_errno().' : '.mysql_error().'<br />');
    mysql_select_db($db);
    $query = 'SELECT * FROM awards WHERE active=1 ORDER BY name';
    $result = mysql_query($query);
    $num = mysql_num_rows($result);

    while ($row = mysql_fetch_array($result)) 
    {
        if ($tags == 'business')
        {
            $where = "SELECT * FROM awards WHERE active=1 AND
tags LIKE '%business%' ORDER BY name";
}
    else if ($tags == 'environmental')
    {
        $where = "SELECT * FROM awards WHERE active=1 AND 
tags LIKE '%environmental%' ORDER BY name";
}
    else if ($tags == 'hospitality')
    {
        $where = "SELECT * FROM awards WHERE active=1 AND 
tags LIKE '%hospitality%' ORDER BY name";
    }
        else
        {
            $where = 'SELECT * FROM awards WHERE active=1 ORDER BY name';
            $title = 'Awards in Alphabetical Order';
        }
    }
    include 'conn.php';
    $connection = mysql_connect($local,$user,$pass) or die (mysql_errno().' : '.mysql_error().'<br />');
    mysql_select_db($db);
    $query = 'SELECT * FROM awards $where';
    $result = mysql_query($query);
    $num = mysql_num_rows($result);
?>

之后,回声等,我没有问题。我似乎无法让它只提取我想要的记录。我会以错误的方式解决这个问题吗?我表中的行“标签”有多个以逗号分隔的值。因此,如果有人选择“业务”,则不应提取任何没有“业务”作为标签之一的记录。我应该将我的“标签”作为单独的行吗?

4

1 回答 1

0
<?php
    $tags = $_GET['tags'];

if ($tags == 'business' || $tags == 'environmental' || $tags == 'hospitality')
{
            $where = "SELECT * FROM awards WHERE active=1 AND
tags LIKE '%$tags%' ORDER BY name";
}
else
{
     $where = 'SELECT * FROM awards WHERE active=1 ORDER BY name';
            $title = 'Awards in Alphabetical Order';
}

include 'conn.php';
$connection = mysql_connect($local,$user,$pass) or die (mysql_errno().' : '.mysql_error().'<br />');
mysql_select_db($db);
$result = mysql_query($where);
$num = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)){
    //echo here whatever u want from the rows fetched with matching tags
}

并且您应该开始使用 PHP PDO 进行数据库访问,因为这里使用的方法很快就会被贬值..

PDO 手册链接

于 2012-08-04T03:38:25.530 回答