0

I searched for similar questions but all I got is "CREATE TABLE IF NOT EXISTS".

That's not what I want at all! I only want to check whether the 5 needed tables exist or not, creating them is an entirely different thing.

Meaning I just want the "IF NOT EXISTS" part, without the "CREATE TABLE". Is there anyway to do it with Idiorm?

P/S: if possible, please write the entire code line (for example ORM::raw_execute('query') or something). I have almost no experience working with database queries :( )

AVAVT
  • 7,058
  • 2
  • 21
  • 44
  • follow this link:http://stackoverflow.com/questions/8829102/mysql-check-if-table-exists-without-using-select-from – user1502952 Aug 26 '13 at 08:27

2 Answers2

1

After spending hours into this, the problem came to: "how do I run execute a sql query in paris/idiorm and get the query result?"

Ididorm's raw_execute() doesn't return the query result but instead return true if the query was executed successfully and false otherwise.

In the end, I solved the problem with:

ORM::for_table('')->raw_query("SQL query to check for existence of the table")->find_one();

Instead of giving a table name as parameter for for_table(), I gave it an empty string then call a raw_query(), which is equivalent to just calling a raw query directly. It worked in my case. I also had to reset Idiorm's db connection and clear the cache for it to work when switching between different dbs.

AVAVT
  • 7,058
  • 2
  • 21
  • 44
  • My version of do this $q = ORM::for_table('') ->raw_query("show tables like 'table_to_be_tested'") ->find_one(); if ($q) { echo "table exist!\n"; } else { echo "table does not exist\n"; } – cwhsu Feb 21 '15 at 03:58
0

On MySql you can query an information_schema.tables view

SELECT n.table_name,
       case when x.table_name is null
            then 'Does not exist'
            else 'Exists'
       end as chk
FROM (
    select 'mytable' as table_name union all
    select 'table1' union all
    select 'tbl1' union all
    select 'another_table' union all
    select 'fifth_table'
) n
LEFT JOIN information_schema.tables x
ON ( x.table_schema = 'test' AND x.table_name = n.table_name );



+ --------------- + -------------- +
| table_name      | chk            |
+ --------------- + -------------- +
| mytable         | Exists         |
| tbl1            | Exists         |
| table1          | Does not exist |
| another_table   | Does not exist |
| fifth_table     | Does not exist |
+ --------------- + -------------- +
krokodilko
  • 35,300
  • 7
  • 55
  • 79