Reputation: 77
I have googled and read a lot about how to create a search in mysql with PDO, but I am still unsuccessful in my attempt on creating one for my self.
Im searching in two fields in my table for the same set of keywords.
$str = explode(' ','app ban');
$p_id = 5;
$search_term = '';
$stmt = $db->prepare('SELECT id from the_table WHERE p_id=:p_id AND (name LIKE :search_term1 OR text LIKE :search_term2)');
$stmt->bindValue(':p_id',$p_id, PDO::PARAM_INT);
$stmt->bindValue(':search_term1',$search_term, PDO::PARAM_STR);
$stmt->bindValue(':search_term2',$search_term, PDO::PARAM_STR);
foreach($str as $key => $value)
{
$search_term = '%'.$value.'%';
$stmt->execute();
while($row = $stmt->fetchObject())
{
if(!isset($res[$row->id]))
$res[$row->id] = 0;
$res[$row->id] = $res[$row->id] + 1*strlen($value);
}
}
print_r($res);
This gives an empty result even though I have the strings 'app' and 'ban' in several fields in both name and text. When I do the same search in phpmyadmin, I get plenty of results.
I have tried with adding some quotes around the keyword: '"%'.$value'%"'; without success. I feel like I'm out of options. Please help!
Upvotes: 0
Views: 143
Reputation: 2540
The two answers above are correct regarding bindValue - it resolves the value only once at the time it is executed. You can use bindParam which is resolved when the ->execute() happens.
as per the PHP bindParam manual page
Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
Upvotes: 2
Reputation: 32232
$search_term
to a blank string$search_term
, but does not re-bind. Upvotes: 0
Reputation: 7643
well you defined $search_term = ''; to empty string, then you used bindValue and used same variable which has the value of empty string.
Inside the loop you tried to assign
$search_term = '%' . $value . '%';
but its already been bound therefore you cant modify it. move your
$stmt->bindValue(':search_term1',$search_term, PDO::PARAM_STR);
$stmt->bindValue(':search_term2',$search_term, PDO::PARAM_STR);
inside foreach loop after
$search_term = '%' . $value . '%';
Upvotes: 1