开发者

insert new rows from db1.table1 into db2.table1

I have two databases($db1, $db2) with exact table structure(table1). $db2.table1 has new rows which i want to insert into $db1.table1 (i.e. if $db2 is new and $db1 is old, I want to update $db1 with n开发者_运维百科ew entries from $db2).

I came up with following php code, and it should work fine, but I am worried about special characters in column ids as well as values to be inserted in it.

Here's the code:

require('update_functions.php'); //contains helper functions

function arraywalk_mysql_real_escape_string(&$value, &$key, $sql_connection) {
    $value = mysql_real_escape_string($value, $sql_connection);
    $key = mysql_real_escape_string($key, $sql_connection);
}

$sql_connection_old = connectdb('old');
$sql_connection_new = connectdb('new');

$table = 'member'; $pkey = 'id'; //table name and primary key
$last_row_member = mysql_fetch_assoc(last_row($sql_connection_old, $table, $pkey));
//fetches last row from old db

$new_row = new_row($sql_connection_new, $pkey, $last_row_member[$pkey], $table, 'ASC LIMIT 1');
//the new_row function executes following query (after sanitizing input)
//'SELECT * FROM '.$table.' WHERE '.$pkey.'>'.$pkey_value.' ORDER BY '.$pkey.' '.$extra

while($result = mysql_fetch_assoc($new_row)) {
    array_walk($result, 'arraywalk_mysql_real_escape_string', $sql_connection_old);
    $update_member_query = 'INSERT INTO ' . $table . '( '
                     . implode(", ", array_keys($insert_vars))
                     . ' ) VALUES ( \''
                     . implode("', '", $insert_vars)
                     . '\' )';

}

I don't know if there will be any special characters in column names. Should I enclose them in backticks?

If yes then should I parse them using mysql_real_escape_srting()?

What about VALUES ? Should I enclose them in quotes 'value'? What if the value to be inserted is a number? what if its Date/Time?

Is there a way where I can bypass fetching data from old database into PHP variables and inserting it back to database (so above questions become irrelevant)?

Note : Even though there are two connections, I have the same SQL server serving the two $db


You can do it in SQL:

INSERT INTO db1.table1
    SELECT * FROM db2.table1 
    WHERE db2.table1.id > (SELECT MAX(id) FROM db1.table1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜