有人問我這個面試問題,所以以爲我會張貼在這裏,看看其他用戶會如何回答:PHP/MySQL面試 - 您將如何回答?
Please write some code which connects to a MySQL database (any host/user/pass), retrieves the current date & time from the database, compares it to the current date & time on the local server (i.e. where the application is running), and reports on the difference. The reporting aspect should be a simple HTML page, so that in theory this script can be put on a web server, set to point to a particular database server, and it would tell us whether the two servers’ times are in sync (or close to being in sync).
這是我提出:
// Connect to database server
$dbhost = 'localhost';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (mysql_error());
// Select database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve the current time from the database server
$sql = 'SELECT NOW() AS db_server_time';
// Execute the query
$result = mysql_query($sql) or die(mysql_error());
// Since query has now completed, get the time of the web server
$php_server_time = date("Y-m-d h:m:s");
// Store query results in an array
$row = mysql_fetch_array($result);
// Retrieve time result from the array
$db_server_time = $row['db_server_time'];
echo $db_server_time . '<br />';
echo $php_server_time;
if ($php_server_time != $db_server_time) {
// Server times are not identical
echo '<p>Database server and web server are not in sync!</p>';
// Convert the time stamps into seconds since 01/01/1970
$php_seconds = strtotime($php_server_time);
$sql_seconds = strtotime($db_server_time);
// Subtract smaller number from biggest number to avoid getting a negative result
if ($php_seconds > $sql_seconds) {
$time_difference = $php_seconds - $sql_seconds;
}
else {
$time_difference = $sql_seconds - $php_seconds;
}
// convert the time difference in seconds to a formatted string displaying hours, minutes and seconds
$nice_time_difference = gmdate("H:i:s", $time_difference);
echo '<p>Time difference between the servers is ' . $nice_time_difference;
}
else {
// Timestamps are exactly the same
echo '<p>Database server and web server are in sync with each other!</p>';
}
是的,我知道,我已經使用了不推薦使用的mysql_ *函數,但是除此之外,你會如何回答,即你會做出什麼改變,爲什麼?我應該考慮哪些因素被忽略?
有趣的是,我的成績似乎總是分鐘的一個確切的數字分開時,我的託管帳戶執行:
2012-12-06 11:47:07
2012-12-06 11:12:07
如果我是面試官,我也不會叫你回來:-) –
使用的DateTime對象,並DateTimeInterval;一點OOP;異常處理db –
謝謝Jack .... – martincarlin87