您可以創建一個類來處理重複執行的任務。這個想法是封裝以後可以用最少量的代碼重用的行爲。這是一個基本的例子。 請記住,您可能想要將數據庫內容(連接,查詢等) 委託給另一個類。另請注意,此類特定於鍵值爲 對的數組(要與具有2列的查詢一起使用)。
<?php
//Takes a two columns SQL query and format it to optain an array with key-value pair
class queryToMap{
private $formattedArray = array(); //The formated array
//Execute the query and format the array
public function executeQuery($sql){
$res = $this->dbQuery($sql);
while($row = $res->fetch_array()){
$this->formattedArray[$row[0]] = $row[1];
}
}
//Returns the formated array
public function getArray(){
return $this->formattedArray;
}
//Execute query and return the result
private function dbQuery($sql){
//DB connection...
$db = new mysqli("localhost", "bob", "123", "db");
//if the query is based on user input, better use prepared statement
$res = $db->query($sql);
return $res;
}
}
//Use of the class
$a = new queryToMap();
$a->executeQuery("SELECT F_CUST_ID, F_CUST_NAME FROM TP_CUSTOMER");
//Output the array
var_dump($a->getArray());
創建可以被實例化或容易填充的對象。一個'read_result_row($ row)'函數,讓他們處理繁重的工作。 – AmazingDreams