加密后CONCAT + TRIM不再起作用

时间:2018-11-07 09:01:04

标签: php sql database concat trim

由于对数据库中的某些信息进行了加密,因此使用现有的搜索功能会遇到很多困难。它的功能是按名字,姓氏或名字搜索学生表。

旧的工作代码如下:

SELECT *
FROM students
WHERE CONCAT(TRIM(firstname), ' ', TRIM(lastname)) LIKE '%$result%'
AND currentyear = $currentyear
ORDER BY students.lastname

经过加密的新的无效代码:

SELECT *, 
       AES_DECRYPT(firstname,UNHEX(SHA2('',512))) AS stfirst,
       AES_DECRYPT(lastname,UNHEX(SHA2('',512))) AS stlast
FROM students
WHERE CONCAT(TRIM(stfirst), ' ', TRIM(stlast)) LIKE '%$result%'
AND currentyear = $currentyear
ORDER BY stlast

我在这里想念一些真正愚蠢的东西吗?谢谢。

2 个答案:

答案 0 :(得分:0)

您不能在条件..的位置使用选择别名。

如果要比较加密的值,还应插入匹配的值

最后尝试使用concat('%',$ result,'%')代替'%$ result%'

SELECT *
  , AES_DECRYPT(firstname,UNHEX(SHA2('',512))) AS stfirst
  , AES_DECRYPT(lastname,UNHEX(SHA2('',512))) AS stlast
FROM students
WHERE CONCAT(TRIM(AES_DECRYPT(firstname,UNHEX(SHA2('',512)))), ' ', 
              TRIM(AES_DECRYPT(lastname,UNHEX(SHA2('',512))))) 
              LIKE TRIM(AES_DECRYPT( concat('%', $result,'%'),
                          UNHEX(SHA2('',512)))))
AND currentyear = $currentyear
ORDER BY stlast

答案 1 :(得分:0)

大概是您在使用MySQL。如果是这样,MySQL会扩展SQL,以便您可以使用带有列别名的HAVING子句,因此,您可以将查询编写为:

SELECT s.*, 
       AES_DECRYPT(firstname,UNHEX(SHA2('', 512))) AS stfirst,
       AES_DECRYPT(lastname,UNHEX(SHA2('', 512))) AS stlast
FROM students s
WHERE currentyear = $currentyear
HAVING CONCAT(TRIM(stfirst), ' ', TRIM(stlast)) LIKE '%$result%' 
ORDER BY stlast;