Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

php - MySQL - using LIKE operator with UNHEX() function

I'm trying to use MySQL function UNHEX() with operator LIKE but i can't get the expected result as $result_2_expected.

What i'm doing wrong?
I'm trying the ways bellow, all without success:

  • LIKE UNHEX('%4272756365%')
  • LIKE '%UNHEX('4272756365')%'
  • LIKE '%UNHEX(4272756365)%'

Experience with Equal operator (Success):

$name_1 = bin2hex("Bruce Wayne"); //4272756365205761796e65
$query_1 = "SELECT `NAME` FROM `USERS_TABLE` WHERE `NAME` = UNHEX('{$name_1}')"; // UNHEX('4272756365205761796e65')


$result_1 = [0][NAME] => "Bruce Wayne"; // Success

Experience with LIKE operator (Fail):

$name_2 = bin2hex("Bruce"); // 4272756365
$query_2 = "SELECT `NAME` FROM `USERS_TABLE` WHERE `NAME` LIKE UNHEX('%{$name_2}%')"; // UNHEX('%4272756365%')

$result_2 = [] => null; // Fail

$result_2_expected = [0][NAME] => "Bruce Wayne"; [1][NAME] => "Bruce Willis"; [2][NAME] => "Bruce Springsteen"; // Expected as Success

question from:https://stackoverflow.com/questions/65918118/mysql-using-like-operator-with-unhex-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that you have put the wildcard characters into the call to UNHEX instead of concatenating them outside it, and that is making UNHEX return NULL, which will always cause LIKE to return false.

Change

LIKE UNHEX('%{$name_2}%')

to

LIKE  CONCAT('%', UNHEX('{$name_2}'), '%')

and your code will work as expected. Alternatively, you could do as @Akina suggested in the comments, and replace the % signs in the call to UNHEX with their hex representation (25) and replace your code with

LIKE UNHEX('25{$name_2}25')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...