您的位置:首页 > 数据库

通过构建SQL语句实现数据同步

2008-09-19 16:07 441 查看
<?php

/**

* @name mysqlbak.php

* @author caleng

* @since 2008-8-1

* @deprecated 实现数据库数据同步

* @version 1.0

*/

/**

* @name connectMysqlServer

* @param string $pHost,$pUser,$pPwd,$pDbName

* @return $conn

* @deprecated connect the mysql db

*/

function connectMySqlServer($pHost, $pUser, $pPwd, $pDbName)

{

$conn = mysql_connect($pHost, $pUser, $pPwd) or die('mysql connect false:'.mysql_error());

mysql_select_db($pDbName, $conn);

return $conn;

}

/**

* @name getMaxTableId

* @param array $pDB = array('host'=>,'user'=>,'pwd'=>,'name'=>,'table'=>,'id'=>'id')

* @return int $id

* @deprecated get the max id value from the $pTable

*/

function getMaxTableId($pDB)

{

$conn = connectMySqlServer($pDB['host'], $pDB['user'], $pDB['pwd'], $pDB['name']);

$sql = "select {$pDB['id']} from {$pDB['table']} order by {$pDB['id']} DESC";

$result = mysql_query($sql, $conn) or die(mysql_error());

return mysql_result($result, 0, $pDB['id']);

mysql_close($conn);

$conn = null;

}

$one = array('host'=>'localhost','user'=>'root','pwd'=>'root','name'=>'china186_main','table'=>'comm_help','id'=>'id');

$tow = array('host'=>'localhost','user'=>'root','pwd'=>'root','name'=>'china186_index','table'=>'comm_help','id'=>'id');

$oneId = getMaxTableId($one);

$towId = getMaxTableId($tow);

if ($oneId > $towId) {

$reId = $oneId - $towId;

//获取源库中不同的数据

$sql = "select * from comm_help limit $towId,$reId";

$conn = connectMySqlServer('localhost','root','root','china186_main');

mysql_query("SET NAMES UTF8");

$result = mysql_query($sql, $conn);

if ($result) {

$reArr = array();

$i = 0;

while ($row = mysql_fetch_assoc($result)) {

$reArr[$i++] = $row;

}//while

}//if

mysql_close($conn);

$conn = null;

//插入到新数据库中

$field = '';

$conn = connectMySqlServer('localhost','root','root','china186_index');

for ($i = 0; $i < count($reArr); $i++) {

$key = implode(',',array_keys($reArr[$i]));

$value = implode("','",$reArr[$i]);

$sql = "insert into comm_help (host,$key) values ('mc2008.china186.com','{$value}')";

mysql_query("SET NAMES UTF8");

mysql_query($sql,$conn) or die(mysql_error());

}

mysql_close($conn);

$conn = null;

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: