CodeIgniter Forums
check if a table exists, if not, create one - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: check if a table exists, if not, create one (/showthread.php?tid=29600)



check if a table exists, if not, create one - El Forum - 04-15-2010

[eluser]ajsie[/eluser]
whenever i use

Code:
// check if table exists
    $query = $this->db->query(
        "SELECT *
        FROM contacts
        LIMIT 1"
    );

to see if a table exists CI shows an error page if it doesnt exist.

i want it to not give me an error. if it doesnt exist i want to create the table.

but at the moment the error page is preventing me from doing so.

could i disable the "ERROR: TABLE DOESNT EXIST" error page?


check if a table exists, if not, create one - El Forum - 04-15-2010

[eluser]eoinmcg[/eluser]
try
Code:
if ($this->db->table_exists('contacts') )
{
  // table exists
}
else
{
  // table does not exist
}



check if a table exists, if not, create one - El Forum - 04-15-2010

[eluser]mddd[/eluser]
edit
Of course, using the CI method for this is even easier than my suggestion below.


Why not use the Mysql command to do that:
Code:
SHOW TABLES
It will get you a result set containing the names of all existing tables. Just check if your table is in that list.


check if a table exists, if not, create one - El Forum - 04-15-2010

[eluser]scieck[/eluser]
To check if a table exists, could you use this instead ?
Code:
// check if table exists
$query = $this->db->query("SHOW TABLES LIKE contacts");



check if a table exists, if not, create one - El Forum - 04-15-2010

[eluser]ajsie[/eluser]
[quote author="scieck" date="1271333455"]To check if a table exists, could you use this instead ?
Code:
// check if table exists
$query = $this->db->query("SHOW TABLES LIKE contacts");
[/quote]

yes it worked. but you had to have single quotes around 'contacts'


check if a table exists, if not, create one - El Forum - 04-15-2010

[eluser]Prophet[/eluser]
You could just let MySQL do the logic:
Code:
CREATE TABLE IF NOT EXISTS 'table_name'

And generate the page based on the result of this query (TRUE/FALSE).