tags:

views:

172

answers:

1

I've already checked answers to questions like this one (How do I create a PDO parameterized query with a LIKE statement in PHP). I've ended up to this solution:

$sql  = "SELECT count(*) ".
        "FROM avs_souscript ".
        "WHERE num_certif =\"\" ".
        "AND date_annul=\"\" ".
        "AND user=:sess_user ".
        "AND user!=\"\" ".
        "AND num_certif LIKE CONCAT('%',:num_certif_search,'%')";
$valeur = 'azert';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':num_certif_search', $valeur);

This works, but here is my problem: how do I handle the '%' char? (i.e. $valeur = '%'; returns all the rows)?

A: 

You need to escape the % character,

  $valeur = '\%';
ZZ Coder
Yep. I knew it. But if you think about the principle: prepare() and bindValue() have been made for both optimization *and* avoiding functions like mysql_real_escape(), escape(), and so on. So if I have to do a str_replace( '%', '\%' ...) this would mean there's one (important) goal missed. That's why I was looking for an elegant solution, instead of feeling like going back to the old "php safe_mode" times.
Olivier Pons
I didn't get your point. Prepared statement has nothing to do with semantics of wildcard. The wildcard character shouldn't change its meaning when used as arguments for prepared statements.
ZZ Coder
What I mean is: old code = "select * from xx where t=".mysql_real_escape(blabla)."<br />new code : prepare("select * from xx where t=:tmp") then bindValue(':tmp', $val). using your suggestion this would give : bindValue(':tmp', str_replace('%', '\%', $val)). This is not clean code to me. We shouldn't use str_replace() here. There has to be another way, because this way is the principle of "escaping unwanted characters", which is a principle that **should** not exist anymore thanks to prepare() and bindValue(). I hope I've been more clear this time :)
Olivier Pons
So, your solution works well, but it's a temporary patch, and I try my best to avoid temporary patches, because I hate them. But thanks anyway, that will do the trick if I can't find a clean solution...
Olivier Pons