catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.83k stars 1.15k forks source link

Problem replacing groups of words larger than 10 elements in WHERE clause using LIKE operator #1109

Closed rickexa closed 7 months ago

rickexa commented 8 months ago

Information

Describe the Problem I had some problem running a select query with LIKE operator: I noticed that when I passed more than 10 elements as argument of the LIKE clause there is an issue in replacing correctly said group of words in the generated query. I don't know if it is a Medoo problem or it's a db side issue but I managed to fix it by slightly modifying the source code.

I show the problem in details.

Let's assume I have an array of 12 words I need to add to my WHERE clause using the LIKE operator.

$word = ["one", "two", "three", ... , "eleven", "twelve"];

The select statement is something like:

$db->select("table", ["title"], ["title[~]" => $words])

which produces the following output of the LIKE part:

"title" LIKE :MeD1_mKL0 OR "title" LIKE :MeD1_mKL1 OR "title" LIKE :MeD1_mKL2 OR "title" LIKE :MeD1_mKL3 OR "title" LIKE :MeD1_mKL4 OR "title" LIKE :MeD1_mKL5 OR "title" LIKE :MeD1_mKL6 OR "title" LIKE :MeD1_mKL7 OR "title" LIKE :MeD1_mKL8 OR "title" LIKE :MeD1_mKL9 OR "title" LIKE :MeD1_mKL10 OR "title" LIKE :MeD1_mKL11)

which is ok and after substituting:

SELECT `title` FROM `amazon` WHERE (`title` LIKE '%one%' OR `title` LIKE '%two%' OR `title` LIKE '%three%' OR `title` LIKE '%four%' OR `title` LIKE '%five%' OR `title` LIKE '%six%' OR `title` LIKE '%seven%' OR `title` LIKE '%eight%' OR `title` LIKE '%nine%' OR `title` LIKE '%ten%' OR `title` LIKE '%two%'0 OR `title` LIKE '%two%'1)

Notice the last 2 elements: title LIKE '%two%'0 OR title LIKE '%two%'1 they are the first and the second words in the array, that's obviously not what I need.

the placeholder :MeD1_mKL10 is matched with :MeD1_mKL1 so it produces %two%0, same for the other placeholder.

The fix I adopted is a simple modification to the index Medoo maps when the LIKE operator is used in the foreach at line 923,

$index = str_pad(strval($index), 3, '0', STR_PAD_LEFT);

In this way, placeholders have all 3 digits and the problem no longer exits.

I repeat, I'm not sure if it's a Medoo related issue or if I missed something in the configuration but you could take a look at the problem and perhaps take this issue into account by implementing a similar change.

Thank you. PS. your library is really super useful!

catfan commented 8 months ago

Thank you for the feedback.

The problem is about the placeholder replacement and I fixed it with simpler code. 1a892c7