Home » Php » php – Is it possible to get the table from a PDOStatement object?

php – Is it possible to get the table from a PDOStatement object?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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'];

Answer:

You can check the query string:

$statement->queryString

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 (SELECT, INSERT, UPDATE, 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.

Answer:

Can you not simply store the string used in the query and use simple string manipulations to access the table?