HuyPV
Wednesday, March 28, 2012
<?php
$time_start = microtime(true);
##############################
define('MAX_TRY', 20);
define('DB_USER', 'root');
define('DB_PASSWORD', 'i-love-me');
define('DB_SERVER', 'localhost');
define('DB_SCHEMA', 'example');
$try = 0;
$conn = @mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
while (!$conn) {
if ($try >= MAX_TRY) {
echo 'I don\'t want to wait anymore :((';
exit;
}
echo '#.# ' . mysql_error() . PHP_EOL;
$try++;
$conn = @mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
sleep(1);
}
echo '^.^ Connected :-w' . PHP_EOL;
mysql_select_db(DB_SCHEMA, $conn);
mysql_query('SET NAMES UTF8', $conn);
for ($i = 0; $i < 100; $i++) {
$result = @mysql_query("SELECT email FROM customers LIMIT $i, 1", $conn);
if ($result) {
$row = mysql_fetch_assoc($result);
if ($row) {
echo 'Got email #' . ($i + 1) . ': ' . $row['email'] . PHP_EOL;
if ($i == 99) $i = -1; // re-loop
} else {
$i = -1; // re-loop
}
} else {
echo 'Try again for #' . ($i + 1) . ' to fix ' . mysql_error() . PHP_EOL;
###
$try = 0;
if ($conn) {
mysql_close($conn); # must have
}
$conn = @mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
while (!$conn) {
if ($try >= MAX_TRY) {
echo 'I don\'t want to try anymore. So tired :((';
exit;
}
echo '#.# ' . mysql_error() . PHP_EOL;
$try++;
$conn = @mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
sleep(1);
}
echo '^.^ Re-connected success' . PHP_EOL;
mysql_select_db(DB_SCHEMA, $conn);
mysql_query('SET NAMES UTF8', $conn);
###
$i--;
}
sleep(3);
}
if ($conn) {
mysql_close($conn);
}
##############################
$time_end = microtime(true);
$time = $time_end - $time_start;
$secs = $time;
echo 'Done! ' . sprintf('%02u:%02u:%02u', $secs / 3600, $secs % 3600 / 60, $secs % 60) . ' seconds';
Title:
PHP CLI reconnect to MySQL
Description:
<?php $time_start = microtime(true); ############################## define('MAX_TRY', 20); define('DB_USER', 'ro...
...
Rating:
4