CodeIgniter基于未定义的字段数搜索数据库?

时间:2013-04-14 19:23:41

标签: mysql database codeigniter search

长期搜索者是第一次问问者。

我使用codeigniter创建一个系统,用户可以使用表单中的一系列字段来搜索结果。这些字段都不是必需的,而是可用于压缩结果。我有它在直接的PHP工作,但在经过一些严肃的搜索后,我无法解决如何在CodeIgniter中使用该功能。我也是该软件的新手。任何建议都将不胜感激。

的index.php

<form action="site/searchcharacter.php" method="post" class="form" id="searchForm">
        <legend>Search AnimeDB</legend>
        <select name="gender"><option>None</option><option>Male</option><option>Female</option></select>
        <select name="approx_age"><option>None</option><option>Baby</option><option>Todler</option><option>Child</option><option>Teen</option><option>Adult</option><option>Senior</option></select>
        <input type="text" name="hair_colour" class="input-small" placeholder="Hair Colour">
        <select name="hair_length"><option>None</option><option>Hair Above Ears</option><option>Hair Below Ears</option><option>Hair Below Shoulders</option><option>Hair Below Waist</option></select>
        <input type="text" name="eye_colour" class="ut-small" placeholder="Eye Colour">
        <select name="ear_type"><option>None</option><option>Human Ears</option><option>Cat Ears</option><option>Dog Ears</option><option>Horns</option><option>Other</option></select>
        <input type="text" name="weapons" class="input-small" placeholder="Weapons">
        <div class="form-actions">
            <button class="btn btn-primary" id="submit_button" type="submit">Search</button>
        </div>
      </form>

searchcharacter.php

$query = "SELECT * FROM characters WHERE 1=1";

    if ($gender != "None") {
        if (!empty($gender)) {
            $query = $query . " AND gender='$gender'";
        }
    }

    if ($age != "None") {
        if(!empty($age)) {
            $query = $query . " AND approx_age='$age'";
        }
    }


    if(!empty($hairColour)) {
        $query = $query . " AND hair_colour='$hairColour'";
    }

    if ($hairLength != "None") {
        if(!empty($hairLength)) {
            $query = $query . " AND hair_length='$hairLength'";
        }
    }

    if(!empty($eyeColour)) {
        $query = $query . " AND eye_colour='$eyeColour'";
    }

    if ($earType != "None") {
        if(!empty($earType)) {
            $query = $query . " AND ear_type='$earType'";
        }
    }

    if(!empty($weapons)) {
        $query = $query . " AND weapons='$weapons'";
    }

    //Prepare and Exec
    $STH = $DBH->query($query);

1 个答案:

答案 0 :(得分:0)

我将从Active Records开始 -

if ($gender != "None" && !empty($gender))
{
  $this->db->where('gender', $gender);
}

然后您可以重复此操作以进行其他检查,因为多个轮胎被添加为链式AND。

然后你拨打$query_result = $this->db->get('characters');