简体   繁体   中英

How to get all the names of the tables involved in a sql query?

For example:

I have this query:

SELECT first_name
FROM users
    INNER JOIN roles ON roles.id = users.id_roles
WHERE roles.name = 'admin';

I need an Array with the name of the tables used in the query,like that:

['users','roles'];

I think this would be tough using regex - unless you know your queries are all consistently following the same standard. Here's an option using EXPLAIN .

$tables = [];
$query = "EXPLAIN SELECT first_name FROM users INNER JOIN roles ON roles.id = users.id_rolesWHERE roles.name = 'admin'";
$q = mysqli_query($link, $query);
while($r = mysqli_fetch_assoc($q)) {
    $tables[] = $r['table'];
}
print_r(array_unique($tables));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM