Chris
Chris

Reputation: 27

PHP PDO & SQL Search wildcard bind parameters

I am trying to create a search function for a site and have created the sql code, which was generated from PHPMYADMIN, see below;

$sql = "SELECT * FROM `bg85ow`.`sessions` WHERE CONVERT(`SessionName` USING utf8) LIKE '%:SessionName1%'";

Here is the PHP code processing the query;

//bind params
                $SessionName1 = filter_input(INPUT_GET, 'search');
                $stmt -> bindValue(':SessionName1', $SessionName1, PDO::PARAM_STR);

                //execute
                $success = $stmt -> execute();

                if (!$success){
                     print $stmt->errorInfo()[2]; //PDO driver error message
                }

                else{
                }

                //array
                $r = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $dbh = null;

                if(!$r)
                {
                    echo "No Results";
                }      

                foreach ((array) $r as $row) {
                 echo $row['SessionId'];
                 echo $row['SessionName'];
                } 

For some reason this will not return any results the execute part is working fine and passing the success test but then once it gets to the array it returns no results.

I checked and $SessionName1 has the term in it from search so it is being passed to the query ok.

When I change the %:SessionName1% to football which is the search term I am testing with, the code returns the results fine but once changed back to :SessionName1 it will not return the results even though the search term is exactly the same.

Can anybody see what I am doing wrong, I spent ages looking at this and cannot see the error.

I have searched everywhere for an answer to this but I couldn't find one specific to this issue, also I am a beginner with PHP and SQL.

Upvotes: 0

Views: 1547

Answers (1)

Monty Khanna
Monty Khanna

Reputation: 1120

Try this Example : Check where is you are wrong.

// Get the keyword from query string
$keyword = $_GET['keyword'];
// Prepare the command
$sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
// Put the percentage sing on the keyword
$keyword = "%".$keyword."%";
// Bind the parameter
$sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);

Upvotes: 3

Related Questions