Say I have a
PDOStatement object generated via
PDO->query($query), is it possible to get the table it was executed on?
Something like this:
<?php $statement = $pdo->query('SELECT * FROM `foo`;'); echo $statement->xyz; // foo
I’m fully aware you can use
$query->getColumnMeta(0)['table'] to do it, but as mentioned by the docs, it’s not very safe. This needs to work across all PDO drivers.
You can retreive the name of the table using the PDOStatement that retrieves an associative array. The value [‘name’] is the name of the table.
$select = $conn_pdo->query('SELECT * FROM foo'); $meta = $select->getColumnMeta(0); echo "Name of table: ".$meta['table'];
You can check the query string:
Remember that a SQL query may reference multiple tables, or no tables, so there is no “table it was executed on”. You could use regular expressions on the query string to find the first table referenced for standard queries (
DELETE), but that may not be perfect.
Alternatively, use models to access your data, and you’ll always know which tables are accessed by the model definition.
Can you not simply store the string used in the query and use simple string manipulations to access the table?