J
J
JackShcherbakov2018-02-02 22:12:12
PHP
JackShcherbakov, 2018-02-02 22:12:12

What does the author mean in this paragraph?

Hello! I am reading a book by David Sklyar in English. Came to the database. I have re-read this paragraph several times, but I do not quite understand the author. What does he mean? What will happen if you use placeholder (substitution symbol, if in Russian) in this situation?
Here is the paragraph itself

// First, do normal quoting of the value
$dish = $db->quote($_POST['dish_search']);
// Then, put backslashes before underscores and percent signs
$dish = strtr($dish, array('_' => '\_', '%' => '\%'));
// Now, $dish is sanitized and can be interpolated right into the query
$stmt = $db->query("SELECT dish_name, price FROM dishes
 WHERE dish_name LIKE $dish");

You can't use a placeholder in this situation because the escaping of the SQL wild-
cards has to happen after the regular quoting. The regular quoting puts a backslash
before single quotes, but also before backslashes. If strtr() processes the string first,
a submitted value such as %chicken% becomes \%chicken\%. Then, the quoting
(whether by quote() or the placeholder processing) turns \%chicken\% into
'\\%chicken\\%'. This is interpreted by the database to mean a literal backslash,
followed by the “match any characters” wildcard, followed by chicken, followed by
another literal backslash, followed by another “match any characters” wildcard.
However, if quote() goes first, %chicken% is turned into '%chicken%'. Then, strt()
turns it into '\%chicken\%'. This is interpreted by the database as a literal percent
sign, followed by chicken, followed by another percent sign, which is what the user
entered.
Thanks in advance!
UPD: The
question was also asked on the English-language forums, but still not finished.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
Bunga, 2018-02-03
@EireenK

If you need to escape wildcards (%, _) in the string for LIKE, you won't be able to use the placeholder, because quoting, performed when substituting into a placeholder, knocks down the escaping of wildcards:
Those. the percentages escaped via strtr turned into full-fledged wildcards again.
To prevent wildcard escaping from crashing, quoting must come before strtr(). Therefore, we remove the placeholder and manually execute quote().

A
Andrew, 2018-02-02
@R0dger

php.net/manual/en/function.strtr.php

K
Konstantin Tsvetkov, 2018-02-02
@tsklab

What does the author mean in this paragraph?
Here is for MS SQL LIKE , read about escape_character.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question