dpb56083 2019-04-12 14:42
浏览 39

无法使用PHP PDO从数据库中检索包含'%'的行

I am making a site that has an autocomplete product search bar. When a user types in a few letters, I compare them to the database with the LIKE statement and get products back that look similar. A user can see a max of 4 products that the user was thinking of in a drop down under the search bar. Now once the user clicks on a result, I pass that back to the PHP PDO statement.

If the product doesn't contain a %, it works fine. But I have products such as '100% Product A', and I can't seem to get around it. I know % is used in the LIKE statement. I used like, but the results weren't great. I was getting a different variation of the product I wanted. How do I get passed this?

$pdo = new PDO($dsn, $user, $passwd);

//Retrieving Product Name
$prodName = $_GET['name'];

$stm = $pdo->prepare("SELECT * FROM products WHERE productName = ?");
$stm->bindValue(1, $prodName);
$stm->execute();

$row = $stm->fetch(PDO::FETCH_ASSOC);

$results[0] = $row["productName"]; 
$results[1] = $row["price"];
$results[2] = $row["quantity"];

$result=implode("','", $results);         
echo $result;
  • 写回答

3条回答 默认 最新

  • dongzhong2018 2019-04-12 14:44
    关注

    Well, i would just remove % from the search string using str_replace

    //Retrieving Product Name
    $prodName = str_replace('%', '', $_GET['name']);
    

    You could also escape the percentage by putting it in brackets or using backslash:

    //Retrieving Product Name
    $prodName = str_replace('%', '[%]', $_GET['name']); // \% would work too instead of [%]
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!