note 108397 modified in pdostatement.bindparam by salathe

From: Date: Mon, 23 Apr 2012 13:16:36 +0000
Subject: note 108397 modified in pdostatement.bindparam by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-187301@lists.php.net to get a copy of this message
when using PDO bindParam to do a search with a LIKE condition, you can prevent user from using LIKE wildcards (&#34;%&#34; and &#34;_&#34;), by escape them to literal using addcslashes or strtr function.&#13;&#10;&#13;&#10;Example:&#13;&#10;&#60;?php&#13;&#10;$query = &#34;SELECT * FROM users WHERE firstname LIKE :keyword&#34;;&#13;&#10;$statement = $handler-&#62;prepare($query);&#13;&#10;&#13;&#10;// Bind the parameter&#13;&#10;$statement-&#62;bindParam(&#39;:keyword&#39;, $keyword);&#13;&#10;&#13;&#10;// escape LIKE wildcards (&#34;%&#34; and &#34;_&#34;) from user input&#13;&#10;// using strtr()&#13;&#10;$keyword = strtr($keyword, array(&#39;\\&#39; =&#62; &#39;\\\\&#39;, &#39;%&#39; =&#62; &#39;\%&#39;, &#39;_&#39; =&#62; &#39;\_&#39;) );&#13;&#10;// or using addcslashes()&#13;&#10;// $keyword = addcslashes($keyword, &#39;%_&#39;);&#13;&#10;&#13;&#10;// add your own LIKE wildcards&#13;&#10;$keyword = &#39;%&#39; . $keyword . &#39;%&#39;;&#13;&#10;&#13;&#10;$statement-&#62;execute();&#13;&#10;// notes: backslash is escape twice, once at SQL quoted string, another at LIKE wildcards string&#13;&#10;// so, backslash from bindParam() will not affect backslash from strtr() or addcslashes()&#13;&#10;?&#62; --was-- when using PDO bindParam to do a search with a LIKE condition, you can prevent user from using LIKE wildcards ("%" and "_"), by escape them to literal using addcslashes or strtr function. Example: <? $query = "SELECT * FROM users WHERE firstname LIKE :keyword"; $statement = $handler->prepare($query); // Bind the parameter $statement->bindParam(':keyword', $keyword); // escape LIKE wildcards ("%" and "_") from user input // using strtr() $keyword = strtr($keyword, array('\\' => '\\\\', '%' => '\%', '_' => '\_') ); // or using addcslashes() // $keyword = addcslashes($keyword, '%_'); // add your own LIKE wildcards $keyword = '%' . $keyword . '%'; $statement->execute(); // notes: backslash is escape twice, once at SQL quoted string, another at LIKE wildcards string // so, backslash from bindParam() will not affect backslash from strtr() or addcslashes() ?> http://php.net/manual/en/pdostatement.bindparam.php

« previous php.notes (#187301) next »