PDO声明使所有参数都相同

时间:2015-09-18 23:58:08

标签: php pdo

我有以下搜索数据库的功能:

public function search($table, $column, $term, $limit = 0, $offset = 0){
        $command = "SELECT * FROM `$table`";
        $size = 1; //1 is for when there is only one LIKE 
         if(is_array($column)){ //Creates the array statemenet
             $size = sizeof($column);
             for($i = 0; $i < $size; $i++){
                 if($i == 0){
                     $command.=" WHERE `$column[$i]` LIKE ?";
                 }else{
                     $command.=" AND `$column[$i]` LIKE ?";
                 }
             }
        }else{//If there's only one
            $command.=" WHERE $column LIKE ?";
        }

    if($limit > 0){//Adds limits
        $command.=" LIMIT ? OFFSET ?";
    }

    echo $command;
    $query = $this->connection->prepare($command);

    if(is_array($column)){
        $x = 0;

        foreach($term as $coldata){
            $x++;
            $type;
            $coldata = "%{$coldata}%";
            $query->bindParam($x, $coldata, PDO::PARAM_STR);
        }
    }else{
        $term = "%{$term}%";
        $query->bindParam(1, $term,  PDO::PARAM_STR);
    }
    if($limit > 0){
        $query->bindParam($size + 1, $limit,  PDO::PARAM_INT);
        $query->bindParam($size + 2, $offset, PDO::PARAM_INT);
    }

    $query->execute();
    return ($query->fetchAll(PDO::FETCH_ASSOC));
}

并且函数的$ column和$ term参数可以是数组。如果它们是数组,则该函数将执行

WHERE x LIKE y AND z LIKE b 

输入东西。

然而,当我测试它时,它会做这样的事情:

Where x LIKE b AND z LIKE b

所有LIKE参数都相同。以下是我提供的示例数据:

$table="tableName"
$column=array('member','type')
$term=array('Bob','admin')
$limit=30
$offset=0

当我查看我的查询日志时,我明白了:

SELECT * FROM `tableName` WHERE `member` LIKE '%admin%' AND `type` LIKE '%admin%' LIMIT 30 OFFSET 0

为什么它在这两个上都使用admin而不是Bob然后管理员这样

SELECT * FROM `tableName` WHERE `member` LIKE '%Bob%' AND `type` LIKE '%admin%' LIMIT 30 OFFSET 0

0 个答案:

没有答案