简体   繁体   中英

PHP / MySQL - Create Table If Not Exist

I have 2 db connections, db1 is the main db and db2 is the copy from.

my script is copying from db2 (has this was the development) to make db1 the same.

However i cannot get the create table if not exist to work with using more then 1 database and using "LIKE".

This is the connection:

<?php
$host = 'localhost';

$db1 = "***";
$username_db1 = '***';
$password_db1 = '***';
$db_c1 = mysql_connect($host, $username_db1, $password_db1) or die('Error connecting to Database!<br>'.mysql_error());

$db2 = "***";
$username_db2 = '***';
$password_db2 = '***';
$db_c2 = mysql_connect($host, $username_db2, $password_db2, true) or die('Error connecting to Database!<br>'.mysql_error());

mysql_select_db($db1, $db_c1);
mysql_select_db($db2, $db_c2);
?>

This is the script well part of it.

$tables1 = array();
$tables2 = array();

$res = mysql_list_tables($db1, $db_c1);
while (list($tmp) = mysql_fetch_row($res))
{
    $tables1[] = $tmp;
}

$res = mysql_list_tables($db2, $db_c2);
while (list($tmp) = mysql_fetch_row($res))
{
    $tables2[] = $tmp;
}

// Tables creates if not exists
foreach($tables2 as $k=>$v)
{
    mysql_query("CREATE TABLE IF NOT EXISTS ".$db1.".".$v." LIKE ".$db2.".".$v, $db_c1);
}

I think the problem is with the LIKE i dont think it is reading it correctly, i have var dumped $tables2 and it does come up with the results.

Thanks

try it in mysql first. drop the table 2 then try your query before doing it dynamically. then one by one change your query to variables. i cant read much from the code but that would be my approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM