Zabindit impossible, and PDO does not have analogs mysql_real_escape_string() . Will it be correct to use PDO::quote() ?
"SELECT * FROM" . $pdo->quote( $table ) ."; Or how then to do in this case?
Let's start with the fallacies.
So, how to add the name of a table or field to a query?
Only through the white list .
Those. after filtering through the list pre-written in the code
There may be many implementation options, one of which was suggested by the author in the comments - read all table names from the database and remember them. This, in principle, can work. Some frameworks even cache this information (for example, Yii). In the case of advanced ORMs, the field-table names are taken from the properties of the corresponding class, again, manually entered.
But if we get bogged down in the old-fashioned way, fulfilling requests directly through the PDO, then the easiest way is to register the available options right before use, especially since there should not be many such cases - otherwise we have obvious design problems.
Plus you need to remember to designate the name of the field or table in accordance with the syntax of the database. For example, for mysql this will be the conclusion of the value in the backtick.
As a result, we get something like this:
if (!in_array($table, ["user","product","catalog"])); { throw new \Exception("Invalid table name!"); } $sql = "SELECT * FROM `$table` WHERE foo = ?" // Π΄Π°Π»Π΅Π΅ ΠΊΠ°ΠΊ ΠΎΠ±ΡΡΠ½ΠΎ Much more frequent is the situation when we need to execute an UPDATE query dynamically if the field names come, say, from $ _POST. The principle remains the same:
/ ΡΠΏΠΈΡΠΎΠΊ Π΄ΠΎΠΏΡΡΡΠΈΠΌΡΡ
Π·Π½Π°ΡΠ΅Π½ΠΈΠΉ $allowed = ["name","surname","email"]; // ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·Π°ΡΠΈΡ ΠΌΠ°ΡΡΠΈΠ²Π° Π΄Π»Ρ Π·Π½Π°ΡΠ΅Π½ΠΈΠΉ $params = []; // ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·Π°ΡΠΈΡ ΡΡΡΠΎΠΊΠΈ Ρ ΠΏΠ°ΡΠ°ΠΌΠΈ `fieldname` = :placeholder $setStr = ""; // ΡΠΈΠΊΠ» ΠΏΠΎ ΡΠ°Π·ΡΠ΅ΡΠ΅Π½Π½ΡΠΌ ΠΏΠΎΠ»ΡΠΌ foreach ($allowed as $key) { if (isset($_POST[$key]) && $key != "id") { $setStr .= " `$key` = ?,"; $params[] = $_POST[$key]; } } $setStr = rtrim($setStr, ","); $params[] = $_POST['id']; $pdo->prepare("UPDATE users SET $setStr WHERE id = ?")->execute($params); SELECT * FROM '".$tablevariable."' where ... Here is the full
mysqli_query($dblink, " SELECT * FROM '".$tablevariable."' "); Source: https://ru.stackoverflow.com/questions/745544/
All Articles
quoteone fig not that. identifiers must be enclosed in quotation marks, not simple. And if it is necessary to check the correctness of the entered table names, then checking the ready list will provide an effective and flexible approach. I do not know what you found there slow. - teran