· 8 years ago · Aug 01, 2018, 03:04 AM
1PHP / MySQL - Create Table If Not Exist
2<?php
3$host = 'localhost';
4
5$db1 = "***";
6$username_db1 = '***';
7$password_db1 = '***';
8$db_c1 = mysql_connect($host, $username_db1, $password_db1) or die('Error connecting to Database!<br>'.mysql_error());
9
10$db2 = "***";
11$username_db2 = '***';
12$password_db2 = '***';
13$db_c2 = mysql_connect($host, $username_db2, $password_db2, true) or die('Error connecting to Database!<br>'.mysql_error());
14
15mysql_select_db($db1, $db_c1);
16mysql_select_db($db2, $db_c2);
17?>
18
19$tables1 = array();
20$tables2 = array();
21
22$res = mysql_list_tables($db1, $db_c1);
23while (list($tmp) = mysql_fetch_row($res))
24{
25 $tables1[] = $tmp;
26}
27
28$res = mysql_list_tables($db2, $db_c2);
29while (list($tmp) = mysql_fetch_row($res))
30{
31 $tables2[] = $tmp;
32}
33
34// Tables creates if not exists
35foreach($tables2 as $k=>$v)
36{
37 mysql_query("CREATE TABLE IF NOT EXISTS ".$db1.".".$v." LIKE ".$db2.".".$v, $db_c1);
38}