我有一個關於PHP類的問題。我想通過PHP獲取Mysql的結果。我想知道是否最佳做法是在類中顯示結果或存儲結果並將其處理爲html。PHP回聲查詢結果在Class中?
例如,類
class Schedule {
public $currentWeek;
function teamQuery($currentWeek){
$this->currentWeek=$currentWeek;
}
function getSchedule(){
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$scheduleQuery=mysql_query("SELECT guest, home, time, winner, pickEnable FROM $this->currentWeek ORDER BY time", $connection);
if (!$scheduleQuery){
die("database has errors: ".mysql_error());
}
while($row=mysql_fetch_array($scheduleQuery, MYSQL_NUMS)){
//display the result..ex: echo $row['winner'];
}
mysql_close($scheduleQuery);
//no returns
}
}
或者返回查詢結果作爲一個變量,在PHP處理這裏
class Schedule {
public $currentWeek;
function teamQuery($currentWeek){
$this->currentWeek=$currentWeek;
}
function getSchedule(){
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$scheduleQuery=mysql_query("SELECT guest, home, time, winner, pickEnable FROM $this->currentWeek ORDER BY time", $connection);
if (!$scheduleQuery){
die("database has errors: ".mysql_error());
// create an array }
$ret = array();
while($row=mysql_fetch_array($scheduleQuery, MYSQL_NUMS)){
$ret[]=$row;
}
mysql_close($scheduleQuery);
return $ret; // and handle the return value in php
}
}
兩件事情裏面顯示的結果:
我發現在PHP中返回的變量有點複雜,因爲它是二維數組。我不確定最佳做法是什麼,並且想問專家的意見。
每次創建一個新的方法,我必須重新創建$連接變量:見下文
$連接的mysql_connect =(DB_SERVER,DB_USER,DB_PASS);如果(!$ connection){ die(「Database connection failed:」。mysql_error()); }
$db_select = mysql_select_db(DB_NAME,$connection); if (!$db_select) { die("Database selection failed: " . mysql_error()); }
這似乎是多餘的給我。我可以只做一次,而不是隨時調用我需要的查詢嗎?我是新來的PHP類。希望你們能幫助我。謝謝。
我只是厭倦了處理二維數組,但我會按照你的建議。非常感謝。 – FlyingCat 2010-05-23 22:10:33
謝謝傑瑞。我也同意prodigitalson,它會更好地使用PDO。另一個建議擺脫二維數組,是創建與數據庫表匹配的類,然後只要獲得二維數組,就可以實例化並返回一個包含結果的類。這使得處理結果變得更加容易和更加標準化,儘管創建額外類的工作有相當多的工作量等。如果您查看PDO提取函數,它甚至可以爲您實例化,而不處理2D數組。或者,看看cakePHP ...太多選項:)祝你好運:) – Jacob 2010-05-23 22:23:51