Skip to content

Instantly share code, notes, and snippets.

@stephenjtong
Created September 24, 2013 10:34
Show Gist options
  • Save stephenjtong/6682991 to your computer and use it in GitHub Desktop.
Save stephenjtong/6682991 to your computer and use it in GitHub Desktop.
多组db query轮查,给出统一结果
<?php
$db_conf = array(
array(
'host' => '1',
'port' => '',
'db' => '1',
'user' => '1',
'pwd' => '1',
),
array(
'host' => '2',
'port' => '',
'db' => '2',
'user' => '2',
'pwd' => '2',
),
...
...
);
function exec_query($query, $count=10){
global $db_conf;
$result = array();
$query = preg_replace('/;$/', '', $query); //如果输入的query后有分号,删掉
$query = $query.' LIMIT '.$count.';';
foreach($db_conf as $db){
$mysqli = new mysqli($db['host'], $db['user'], $db['pwd'], $db['db']);
if ($mysqli->connect_errno) {
printf("Connect failed %s: %s\n", $db['host'], $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$tmp_result = $mysqli->query($query);
while ($row = $tmp_result->fetch_assoc()) {
$result[] = $row;
}
$mysqli->close();
}
return $result;
}
if(count($argv)>1 && $argv[1]!= 'command'){
$limit = isset($argv[2]) ? $argv[2] : 15;
$rs = ( exec_query($argv[1], $limit));
if(empty($rs)){
echo "no results\n";
die;
}
$keys = array_keys($rs[0]);
foreach($keys as $key){
echo "$key\t";
}
echo "\n";
foreach($rs as $r){
foreach($keys as $key){
echo "$r[$key]\t";
}
echo "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment