doubiantiao4994 2015-08-11 18:06
浏览 22
已采纳

php条件连接不起作用

So for some reason I need to check whether password should change or not. for that I use a variable to see if it's true or false.

$query  = "UPDATE c_users SET ";
$query .= ($changepass) ? "user_pass = '$password', " : '' . "user_email = '$email', user_role = $role, display_name = '$nick', WHERE ID = $id";

echo $query . "<br>";

This works fine if ($changepass) is false and if I print it:

UPDATE c_users SET user_email = 'example@example.com', user_role = 3, display_name = 'ROBOT', vip_status = 1 WHERE ID = 550

however if ($changepass) is true, it doesn't work as expected. It should append user_pass = '$password', to rest of the statement but instead it prints this:

UPDATE c_users SET user_pass = '$2y$10$l1TylEhM2oz4WdmlwWkcaupjpj1tt/HCyn7XGWbep1judDQb3E7e.',

notice that rest of the statement is missing. so query fails. how to fix it?

  • 写回答

1条回答 默认 最新

  • douyong1974 2015-08-11 18:18
    关注

    That's because your ternary is effectively:

    if ($changepass) {
        $query .= "user_pass = '$password', ";
    } else {
        $query .= '' . "user_email = '$email', user_role = $role, display_name = '$nick', WHERE ID = $id";
    }
    

    So it never appends the additional set values if $changepass is true

    To achieve what you want, you need to do

    $query .= ($changepass) ? "user_pass = '$password', " : '';
    $query .= "user_email = '$email', user_role = $role, display_name = '$nick', WHERE ID = $id";
    

    But you really should be entering the 21st century and using prepared statements with bind variables in 2015

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

报告相同问题?

悬赏问题

  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示
  • ¥15 MATLAB有限差分法解一维边值问题
  • ¥200 内网渗透测试 横向渗透 Windows漏洞 Windows权限维持
  • ¥15 数据结构图的相关代码实现
  • ¥15 python中aiohttp.client_exceptions.ContentTypeError
  • ¥30 DeepLung肺结节检测生成最大froc值对应的epoch报错
  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家