doue2666 2012-04-04 21:34
浏览 106
已采纳

使用PHP将MySQL字段强制为小写

I have a database with an email field, and it cycles through the database to grab all the transactions concerning a certain email address.

Users putting in lowercase letters when their email is stored with a couple capitals is causing it not to show their transactions. When I modify it to match perfect case with the other emails, it works.

How can I modify this so that it correctly compares with the email field and case doesn't matter? Is it going to be in changing how the email gets stored?

$result = mysql_query("SELECT * FROM `example_orders` WHERE `buyer_email`='$useremail';") or die(mysql_error());

Thanks ahead of time!

  • 写回答

3条回答 默认 最新

  • dqoag62688 2012-04-04 21:41
    关注

    A mixed PHP/MySQL solution:

    $result = mysql_query("
        SELECT * 
        FROM example_orders
        WHERE LOWER(buyer_email) = '" . strtolower($useremail) . "';
    ") or die(mysql_error());
    

    What it does is converting both sides of the comparison to lowercase. This is not very efficient, because the use of LOWER will prevent MySQL from using indexes for searching.

    A more efficient, pure SQL solution:

    $result = mysql_query("
        SELECT * 
        FROM example_orders
        WHERE buyer_email = '$useremail' COLLATE utf8_general_ci;
    ") or die(mysql_error());
    

    In this case, we are forcing the use of a case-insensitive collation for the comparison. You wouldn't need that if the column had a case-insensitive collation in the first place.

    Here is how to change the column collation, as suggested by Basti in a comment:

    ALTER TABLE `example_orders` 
    CHANGE `buyer_email` `buyer_email` VARCHAR( 100 ) 
       CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
    

    If you choose to do that, you can run the query without COLLATE utf8_general_ci.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥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,如何解決?
  • ¥15 c++头文件不能识别CDialog