Created
March 11, 2013 06:47
-
-
Save tg123/5132287 to your computer and use it in GitHub Desktop.
php code to sync tables
primay key name should be id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function coltable($db, $table){ | |
$stmt = $db->prepare("DESC $table"); | |
$stmt->execute(); | |
return array_map(function($v){ | |
return strtolower($v['Field']); | |
}, $stmt->fetchAll(PDO::FETCH_ASSOC)); | |
} | |
function select($db, $cols, $table, $min, $max){ | |
$sql = "SELECT `" . join('`,`',$cols) . "` FROM `$table` WHERE `id`>= :min AND `id`<:max"; | |
$stmt = $db->prepare($sql); | |
$stmt->bindValue(':min', $min); | |
$stmt->bindValue(':max', $max); | |
$stmt->execute(); | |
return $stmt->fetchAll(PDO::FETCH_ASSOC); | |
} | |
function selectAllWithCol($db, $cols, $table, $dealrow){ | |
$f = function($db, $table, $act){ | |
$stmt = $db->prepare("SELECT $act as i FROM $table"); | |
$stmt->execute(); | |
$row = $stmt->fetch(PDO::FETCH_ASSOC); | |
return $row['i']; | |
}; | |
$min = $f($db, $table, 'min(id)'); | |
$max = $f($db, $table, 'max(id)'); | |
$countAsterisk = $f($db, $table, 'count(*)'); | |
if(!$countAsterisk){ | |
return; | |
} | |
$step = max(($max - $min) / $countAsterisk, 500); | |
for ($i = $min; $i < $max;) { | |
$lower = $i; | |
$upper = min($lower + $step, $max); | |
$i = $upper + 1; | |
foreach(select($db ,$cols, $table, $lower, $upper) as $r){ | |
$dealrow($r); | |
} | |
} | |
} | |
function selectAll($db, $table, $dealrow){ | |
$cols = coltable($db, $table); | |
return selectAllWithCol($db, $cols, $table, $dealrow); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
// sync 4 tables with | |
foreach(array('table1','table2','table3','table4') as $t){ | |
$c = 0; | |
$cols = coltable($db, "old_$t"); | |
selectAll($db, "old_$t",function($r){ | |
global $cols , $t ,$c; | |
$target = "new_$t"; | |
$db = .... ; // NEW DB | |
$sql = buildinsert($cols, $target); | |
$stmt = $db->prepare($sql); | |
foreach($r as $k => $v){ | |
$stmt->bindValue(":$k", $v); | |
} | |
$stmt->execute(); | |
echo "$t ->" . $c++ . "\n"; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment