简体   繁体   中英

PHP PDO LIKE statement unsuccessful

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!

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.

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 . '%'; 
  1. You set $search_term to a blank string
  2. You bind both search terms as the blank string
  3. You then enter a loop that re-sets the value of $search_term , but does not re-bind.
  4. Then, for some reason, you execute the query and retrieve results while still inside the loop from #3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM