duanruinong0619 2014-04-12 15:36
浏览 620
已采纳

从mysql表中检索数据时如何忽略空格

I am working in PHP with PDO. The problem I am having is: I have a table called products. It has a column named product_name. Here are some examples of the name of products

product_name
----------
Bfilet de bœuf entier                    
Bar de ligne                             
Saumon entier
Beurre 

So when I execute the query

select * from products where product_name='beurre'

It works fine. It returns the corresponding line.

But if I do:

select _ from products where product_name='Saumon entier'"

It does not return any result. There seems to be a problem when there are spaces involved!

And another unusual thing is that I don't seem to be having this problem on the SQL Command line, only when I use PHP to retrieve the data.

Could someone explain to me why and offer a solution?

  • 写回答

1条回答 默认 最新

  • dongwei9365 2014-04-12 15:41
    关注

    Pattern matching

    Lookup MySQL pattern matching. Code would be something like:

    $stmt = $pdo->prepare('SELECT * FROM products WHERE product_name LIKE ?');
    $stmt->execute(['Saumon entier%']);
    
    var_dump($stmt->fetchAll());
    

    After your edit, it appears you don't want LIKE, but you actually have a space at the end of the string. Quick fix would be:

    SELECT * FROM products WHERE TRIM(product_name) = 'Saumon entier'
    

    But really you should trim spaces on input.

    Answer to question in comments

    if i have a french product name such as 'Côte de bœuf', Is there a way i can replace the accents?

    In most cases, yes. If your database is utf8 with e.g. utf8_unicode_ci, while ci meaning case-insensitive this would match:

    SELECT 'Côte de boeuf' = 'cote de boeuf';
    
    'Côte de boeuf' = 'cote de boeuf'
    ----------------------------------
                                     1
    

    Note that I removed œ because that won't match, I am not sure to which character it translates. Other option would be to store "non accented" product name in different column and match against those. Lookup iconv in PHP manual.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?