redGREENblue
redGREENblue

Reputation: 3126

Proper way to pass %like% param with PDO?

Here's the query below,

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;
    }

Error I am getting is

Fatal error: Cannot pass parameter 2 by reference in

I guess I am doing the like param incorrectly (as it works for where = condition). I am pretty new to slim, any help?

Upvotes: 1

Views: 63

Answers (3)

Saty
Saty

Reputation: 22532

<?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;
    }

Search string in where condition so it would be s and add PDO::PARAM_STR

Upvotes: 2

mim.
mim.

Reputation: 677

You need to set where your i variable goes.

$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

Upvotes: 2

Jay Blanchard
Jay Blanchard

Reputation: 34426

You have to form the string before you can use it in 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;
}

In addition it looks like you're passing a string, not an integer, make sure you set the type to "s"

Upvotes: 3

Related Questions