I am connecting to an SQL Server DB via PDO in PHP. My question is why can I not bind parameters to named place markers every time a while loop runs? Here's the code:
public function search($search, $field)
{
$c = new PDO("sqlsrv:Server=localhost;Database=$this->_db", $this->_user, $this->_pass);
$sql = "
SELECT Title
FROM Table WHERE 1=1";
//form array of search terms stored in serachArray variable
$searchArray = explode(' ', $search );
//count objects in array
$num_search_terms = count( $searchArray );
$i = 0;//for search term array (starts at 0)
$x = 1;//for parameter incrementin (starts at 1)
while( $i <= ( $num_search_terms -1 ) )
{
$sql .= "
AND $field LIKE :s".$x;
$stmt = $c->prepare( $sql );
$currTerm = "%" . $searchArray[ $i ] . "%";
$stmt->bindParam( ':s'.$x, $currTerm );
$i++;
$x++;
}
$stmt->execute();
while ( $row = $stmt->fetch( PDO::FETCH_OBJ ) )
{
print $row->Title;
}
}
The result set is returning empty with no errors. There should definitely be data returned from this search. When I only enter one search term it works fine. However when I enter more than one I always get no results.