0

I have following query:

CREATE TABLE `test` (
`col1` INT( 10 ) NOT NULL ,
`col2` VARCHAR( 50 ) NOT NULL ,
`col3` DATE NOT NULL
) ENGINE = MYISAM ;

I want to write a general php script that get table name(test) from above query.

5
  • you can use regular expressions. are all input queries of type CREATE TABLE? Commented Jun 12, 2011 at 17:17
  • what will be regular expression. I am not good in regular expressions.. Commented Jun 12, 2011 at 17:18
  • if all your queries are CREATE TABLE, you can split it and just get the 3rd word, right? Commented Jun 12, 2011 at 17:18
  • Yes. It is always create query in this case. Commented Jun 12, 2011 at 17:23
  • pear.php.net/package/SQL_Parser might solve this task in a more generic way. Commented Jun 12, 2011 at 17:32

1 Answer 1

1

If you can access the string which gets queried before you run the query, you can do this:

preg_match("/^create table `(?P<tablename>)`/i", $query, $matches);
print_r($matches);

/* 
    Output:
    Array
    (
        [0] => CREATE TABLE `test` (`col1` INT( 10 ) NOT NULL ,`col2` VARCHAR( 50 ) NOT           NULL , `col3` DATE NOT NULL ) ENGINE = MYISAM ;
        [tablename] => test
        [1] => test
     )
*/

If you can't access the string for some reason, but you know that nothing is created in the database between the query and your code then you can use this query to retrieve the last created table:

SELECT 
    *
FROM 
    information_schema.TABLES
ORDER BY 
    CREATE_TIME DESC
LIMIT 
    1;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.