how to extract table names from mysql query with php?

mysql, php, regex

Solution

sorry... here a solution to extract it (if your query in `$query`)

if(preg_match_all('/((FROM|JOIN) `(.*)`)/', $query, $matches)) {
    $tables = array_unique($matches[3]);
    print_r($tables);
}

Problem

I wanna detect all tables in an mysql query with php. I saw mysql_field_table() function that is work for normal queries. but when you use alternative name for a table (table_name AS new_name) it return alternative name not the real name, how ever I fix it by a regex. but now my problem is now with advanced queries like this: ``` SELECT mail_id, mail_date, mail_from, mail_to, mail_subject, ( ( SELECT COUNT(*) FROM `sys_messagecenter_qmails` WHERE qmail_mail_id = mail_id ) + ( SELECT COUNT(*) FROM `sys_messagecenter_rels` WHERE rel_mail_id = mail_id ) ) AS email_total, ( SELECT COUNT(*) FROM `sys_messagecenter_rels` WHERE rel_mail_id = mail_id ) AS email_sent, ( SELECT COUNT(*) FROM `sys_messagecenter_rels` INNER JOIN `sys_email_receives` ON receive_reply_to = rel_sent_id WHERE rel_mail_id = mail_id ) AS email_reply FROM `sys_messagecenter_emails` WHERE mail_draft='No' ORDER BY mail_id ASC LIMIT 0,10 ``` now I think I need some regex for detect all real table names in a query. or any other perfect solution. how can I do this?

Original source