r/PHPhelp • u/AdmirableSandwich393 • Mar 12 '25
Binding table names - does it work or no?
I have read, and been instructed on numerous times, that binding a table name for a SQL query will not work. And yet... Here is my code:
$uName = $_SESSION["user_userName"];
function list_user_info($uName) {
$query = "SELECT * FROM `:userName`;";
$stmt = $pdo->prepare($query);
$stmt->bindParam(":userName", $uName);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
And yet, it will show the contents of the table name based on who is logged in at the time.
1
Upvotes
4
u/Big-Dragonfly-3700 Mar 13 '25
How did you create this table? Did you use php/PDO with a prepared query to supply the table name?
Here's why this likely works. You are using an emulated prepared query and you are using back-tacks around the table name/identifier in the query. The emulator is adding single-quotes around the value when it builds the sql query statement. Inside of a back-tick 'quoted' identifier, all ASCII characters, except null are permitted, so you have a table name that is literally
'some_name'including the single-quote characters as part of the name.I'm betting that if you look closely at the table definition, the name actually has leading and trailing single-quotes as part of it.
2
u/colshrapnel Mar 12 '25
I don't think so. In theory, it could have worked for sqlite, but it seems there is no emulation mode for it. And for other DBMS it won't work for sure. So I am afraid you have to provide a working example on https://phpize.online/ before making such a claim.
Besides, this code makes no sense on another layer: why would you create a table named after a user? It's more likely that your query looks like
which would certainly work
1
u/rx80 Mar 13 '25 edited Mar 13 '25
If you read: https://www.php.net/manual/en/pdo.setattribute.php
you will see:
So, my guess is that your prepared statement fails at the driver level, and it's then emulated & fixed on the PDO level.
Edit: So, the only way to properly convince yourself that the DB fails at this is to use native commands to prepare a query, for example in MariaDB:
The above will fail, but this will work:
1
u/[deleted] Mar 12 '25
[removed] — view removed comment