doudou201701 2015-11-30 17:03
浏览 84
已采纳

为什么这个'case'查询在codeigniter中没有返回'true'或'false'

I have a query that checks if a row from a table exists. It should return a 'true' or 'false' value, but this is not the case.

The query and code look as follows. I should mention that I use the CodeIgniter framework, hence the object names and function names.

$query="SELECT CASE WHEN EXISTS
                (
                SELECT * FROM Users
                WHERE Email=".$this->db->escape($email)."
                AND PassWord=MD5(".$this->db->escape($password).")
                )
                THEN 'TRUE'
                ELSE 'FALSE'
                END";

            $result=$this->users_db->query($query);  
            $resulting_array=$result->row();

            echo "<pre>".var_dump($resulting_array)."</pre>";

This code gives the following result:

object(stdClass)#22 (1) {
  ["CASE WHEN EXISTS
                (
                SELECT * FROM Users
                WHERE Email='r.blaauwen@erasmusmc.nl'
                AND PassWord=MD5('rrt')
                )
                THEN 'TRUE'
                ELSE 'FALSE'
                END"]=>
  string(5) "FALSE"
}

It seems $result->row(); delivered an object instead of an array/string/boolean. The 'FALSE' result is there, but I don't know how to retrieve it.

  • 写回答

2条回答 默认 最新

  • duanlan4801 2015-11-30 17:11
    关注

    MySQL has no boolean type, so if you want to treat the response as boolean, you should use 0 or 1.

    Next, CodeIgniter's database class is returning a standard object, but it's not very accessible because you're selecting something that isn't named. If you alias the field, then you can access it easier:

    $query="SELECT (CASE WHEN EXISTS
                (
                  SELECT * FROM Users
                  WHERE Email=".$this->db->escape($email)."
                  AND PassWord=MD5(".$this->db->escape($password).")
                )
                THEN 1
                ELSE 0
                END
            ) AS userExists";
    $result=$this->users_db->query($query);  
    $resulting_array=$result->row();
    
    if ($resulting_array->userExists) {
        echo "User Exists!";
    } else {
        echo "Invalid password/no user";
    }
    

    Finally, using MD5 to hash passwords is a really bad idea. Take a read of the official PHP documentation about passwords to see why:

    Why are common hashing functions such as md5() and sha1() unsuitable for passwords?

    Hashing algorithms such as MD5, SHA1 and SHA256 are designed to be very fast and efficient. With modern techniques and computer equipment, it has become trivial to "brute force" the output of these algorithms, in order to determine the original input.

    Because of how quickly a modern computer can "reverse" these hashing algorithms, many security professionals strongly suggest against their use for password hashing.

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

报告相同问题?