使用PDO传递%like%param的正确方法?

时间:2015-05-12 12:05:31

标签: php mysql

以下是查询,

public function getSearchResult($searchString){
       $stmt = $this->conn->prepare("SELECT t.* FROM company t WHERE t.company_name like ? ");
        $stmt->bind_param("i", "%".$searchString."%");
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;
    }

我得到的错误是

  

致命错误:无法通过

中的引用传递参数2

我想我正在做错误的param(因为它适用于where = condition)。我很擅长苗条,有什么帮助吗?

3 个答案:

答案 0 :(得分:3)

您必须先形成字符串,然后才能在bind_param()

中使用它
public function getSearchResult($searchString){
   $search = '%'. $searchString . '%';
   $stmt = $this->conn->prepare("SELECT t.* FROM company t WHERE t.company_name like ? ");
   $stmt->bind_param("s", $search);
   $stmt->execute();
   $tasks = $stmt->get_result();
   $stmt->close();
   return $tasks;
}

此外,看起来就像传递字符串而不是整数一样,请确保将类型设置为"s"

答案 1 :(得分:2)

您需要设置i变量的位置。

$stmt = $this->conn->prepare("SELECT t.* FROM company t WHERE t.company_name LIKE :i ");
$stmt->bind_param(":i", "%$searchString%", PDO::PARAM_STR);

Here is an example in php.net

答案 2 :(得分:2)

<?php
public function getSearchResult($searchString){
       $stmt = $this->conn->prepare("SELECT t.* FROM company t WHERE t.company_name like ? ");
        $stmt->bind_param("s", "%$searchString%",PDO::PARAM_STR);
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;
    }

在条件中搜索字符串,以便它s并添加PDO::PARAM_STR