如何在select中创建一个选项值以查找任何值

时间:2014-06-09 10:08:11

标签: php mysql

这是项目的示例表:

TBL_TEST:

id     -
reference   -
reciever   -
created-

这是视图,在添加类并包含所有必需的文件(如db_con和类初始化)以及创建新对象之后。

$refone = $_POST['refone'];
$reftow = $_POST['reftow'];
$ref3= $documentout->get_ref($refone,$reftow);
foreach($ref3 as $ref):
    echo "this is test ".$ref['reference']."--------" .$ref['reciever']. "<br />";
endforeach;
    <form method="POST" action="">
    <lable>select_ref1</lable>
      <select name="refone">
        <option value=''>all</option>
        <option value='1'>one</option>
       <option value='2'>tow</option>
      </select>
    <lable>select_ref2</lable>
      <select name="reftow">
        <option value=''>all</option>
        <option value='1'>one</option>
       <option value='2'>tow</option>
      </select></form>

这是回显结果的函数:

public function get_ref($refone, $reftow) {
        $query = 'SELECT * FROM '. self::$table_name . ' WHERE reference = :refone AND reciever = :reftow';
        $sth = $this->conn->prepare($query);
        $sth->bindParam('refone', $refone, PDO::PARAM_INT);
        $sth->bindParam('reftow', $reftow, PDO::PARAM_INT);
        $sth->execute();
        return $row = $sth -> fetchAll();
    }

现在她是idia,我想要回复 reference =%any%and reciever =%what% 表示全部选择或全部选择,因此它应该全部结果。

4 个答案:

答案 0 :(得分:1)

根据您的意愿做一些逻辑来进行查询,一个解决方案可以使用ifs进行配置(比如之前的两个答案&#34;。我建议你使用PDO来创建查询。你能看到{{ 3}}

示例最终查询字符串并执行它:

$query = 'SELECT * FROM table WHERE ref1 = :ref1 AND ref2 = :ref2';
$sth = $db->prepare($query);
$sth->bindParam('ref1', $ref1, PDO::PARAM_INT);
$sth->bindParam('ref2', $ref2, PDO::PARAM_INT);
sth->execute();

答案 1 :(得分:0)

做一点点不同并动态创建你的sql语句

将您的<option value="">all</option>更改为<option value="all">all</option>

然后使用一系列if语句

if ($_GET['ref1']!="all")  {
   //nothing comes before this so you can not worry about an AND
   $ref1sql = "ref1 =" . $_GET['ref1'];
}


if ($_GET['ref2']!="all")  {
   //so we have a ref2 here check if there's a ref  1
   if ($_GET['ref1']!="all")  {
       //we have a ref1 so need an and
       $ref2sql = " AND ref2 =" . $_GET['ref2'];
   } else {
       $ref2sql = "ref2 =" . $_GET['ref2'];
   }
}

$query = "SELECT * FROM TBL_TEST WHERE $ref1sql $ref2sql";

答案 2 :(得分:0)

像这样更改all选项值

<option value='all'>all</option>

php

$ref1 = $ref2 = 1;

if($_GET['ref1'] != '' && $_GET['ref1'] != 'all') {
   $ref1 = 'ref1 = ' . $_GET['ref1'];
}

if($_GET['ref2'] != '' && $_GET['ref2'] != 'all') {
   $ref2 = 'ref2 = ' . $_GET['ref2'];
}

$query = "SELECT * FROM TBL_TEST WHERE $ref1 AND $ref2 "; 

答案 3 :(得分:0)

问题是您传递的选项All的值。如果你不想改变你的PHP代码,你应该尝试

<option value="%">all</option>