您可以创建一个类来处理重复性任务。这个想法是用最少的代码封装你以后可以重用的行为。这是一个基本的例子。请记住,您可能希望将数据库内容(连接、查询等)委托给另一个类。另请记住,此类特定于具有键值对的数组(用于具有 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());