简体   繁体   English

LIKE语句和PDO / PHP中的特殊字符

[英]LIKE statement and special characters in PDO / PHP

I've already checked answers to questions like this one (How do I create a PDO parameterized query with a LIKE statement in PHP) . 我已经检查过这样的问题的答案(如何在PHP中使用LIKE语句创建PDO参数化查询) I've ended up to this solution: 我最终得到了这个解决方案:

$sql  = "SELECT count(*) ".
        "FROM mytable ".
        "WHERE num_certif LIKE CONCAT('%',:val,'%')";
$valeur = 'azert';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':val', $val);

This works, but here is my problem: how do I handle the ' % ' char? 这有效,但这是我的问题:我如何处理' '字符? (ie $valeur = '%'; returns all the rows)? (即$ valeur ='%';返回所有行)?

你需要转义%字符,

  $valeur = '\%';

Note for PostgreSQL users... instead of the CONCAT function you can use 注意PostgreSQL用户...而不是你可以使用的CONCAT功能

   SELECT count(*)
   FROM mytable
   WHERE num_certif LIKE '%' || :val || '%'

I achieved that using string comparison functions: 我使用字符串比较函数实现了:

WHERE INSTR(LCASE(num_certif),LCASE(:val))>0

I suspect performance will suffer. 我怀疑表现会受到影响。

I have been using something very simple, like this: 我一直在使用非常简单的东西,像这样:

    $select_str = "SELECT * FROM table_x WHERE text_field LIKE '%".$value."%'";

    $StHandler = $this->dbHandler->prepare($select_str);
    $StHandler->execute();

You can use only one % depending on what you're looking for. 根据您的要求,您只能使用一个百分比。 For example, if you want it to start with your value and have any characters later, you will use '".$value."%'" 例如,如果您希望它以您的值开头并且稍后有任何字符,您将使用'“。$ value。”%'“

Hope this helps 希望这可以帮助

In order to avoid having to do your own escaping, the stuff that needs to be escaped has to be part of the data that pdo protects, namely the bound arguments. 为了避免必须进行自己的转义,需要转义的东西必须是pdo保护的数据的一部分,即绑定的参数。 It doesn't protect you from anything in the hard coded query. 它不会保护您免受硬编码查询中的任何操作。

$sql  = "SELECT count(*) ".
    "FROM avs_souscript ".
    "WHERE num_certif =\"\" ".
    "AND date_annul=\"\" ".
    "AND user=:sess_user ".
    "AND user!=\"\" ".
    "AND num_certif LIKE :num_certif_search";
$valeur = 'azert'; //I assume this actually came from some user input
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':num_certif_search', '%'.$valeur.'%');

(or alternately you could put them in the $valuer = "%{$userInput}%"; assignment, either way, they should be in the bound argument, not in the sql. (或者你可以把它们放在$valuer = "%{$userInput}%";赋值,无论哪种方式,它们应该在绑定参数中,而不是在sql中。

Moving this bit of silly string concat from the sql out to the php is also good practice for making a scalable application. 将这段傻字符串连接从sql移出到php也是制作可伸缩应用程序的好习惯。 It's much easier to scale a farm of web servers than it is to scale the database server. 扩展Web服务器场比扩展数据库服务器要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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