簡體   English   中英

有沒有更優雅的方法可以在PHP中格式化MySQL結果?

[英]Is there a more elegant way to format MySQL results in PHP?

經過幾年的發展,我只是問自己,是否有一種更優雅的方式將MySQL結果格式化為如下所示的關聯數組。

這里有一些偽代碼,顯示了我通常的做法。

$sql = 'SELECT field1, field2 FROM sample_table';
$res = $db->prepare($sql)->getAll();
$formatted = array();

foreach ($res as $row) {
    $formatted[$row['field1']] = $row['field2'];
}

當我經常做這樣的事情時,我問自己是否有一種更優雅或更快捷的方法。

謝謝!

您可以創建一個類來處理重復任務。 這個想法是封裝行為,您以后可以用最少的代碼重用這些行為。 這是一個基本示例。 請記住,您可能希望將數據庫內容(連接,查詢等)委派給另一個類。 還要記住,該類特定於具有鍵-值對的數組(與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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM