2014-09-03 25 views
-2

我有SQL DB與一些表。我想知道是否有任何方法可以構建帶有某些字段和函數的類,併爲此表中的每一行創建此類的實例,並稍後在JS代碼中使用這些對象來顯示對象某些方式爲用戶? 我是網絡開發新手,所以我可能不清楚..對不起。如何使一個SQL表格行作爲PHP中的對象

+0

這是如此的幫助..感謝.. – user3787639 2014-09-03 19:37:09

+2

http://php.net//manual/bg/mysqli-result.fetch-object.php – bksi 2014-09-03 19:39:38

+0

http://stackoverflow.com/a/13084958/1729885 – 2014-09-03 19:44:34

回答

2

例如,您正在尋找的是像Propel或Doctrine這樣的對象關係映射器(ORM)。 ORM提供了您的PHP對象和底層SQL數據庫之間的映射。

爲了在您的JavaScript應用程序中訪問這些對象,您需要使用適當的文本表示來傳送它們。最常見的格式是JSON,它是ECMA標準的一部分。使用文本表示,對象可以直接在JavaScript中集成或使用AJAX調用獲取。

1

以下是一些可能提供有用模型的示例代碼。

class community { 
public $community_id; 
public $name; 
public $handle; 
public $parent_comm_id; 
public $shortname; 

public static $COMMUNITIES = array(); 

function __construct($community_id, $name, $handle, $parent_comm_id) { 
    $this->community_id = $community_id; 
    $this->name = $name; 
    $this->handle = $handle; 
    $this->parent_comm_id = $parent_comm_id; 

    self::$COMMUNITIES[$community_id] = $this; 
} 


public static function initCommunities() { 
    $dbh = $GLOBALS['dbh']; 
    $sql = <<< EOF 
    select community_id, name, handle, parent_comm_id 
    from community 
    inner join handle on community_id = resource_id and resource_type_id = 4 
    left join community2community on child_comm_id = community_id 
    order by name; 
EOF; 

    $result = pg_query($dbh, $sql); 
    if (!$result) { 
     die("Error in SQL query: " . pg_last_error()); 
    }  

    while ($row = pg_fetch_array($result)) { 
     new community($row[0], $row[1], $row[2], $row[3]); 
    }  

    // free memory 
    pg_free_result($result);  
} 
} 
相關問題