2010-09-23 71 views
1

我使用的是php和postgresql。把查詢結果放入對象中

我需要一個函數:

連接到一個數據庫,如果沒有連接 運行查詢安全 把結果放到對象

例如: 我做一個查詢是「選擇*來自測試'。我找回2行...'test'(id,fname,lname)中有三列。

我有一個名爲$ ep的對象。我希望能夠將列名稱結果放入對象中,並將值放入對象中。所以我可以做一個$ ep-> fname的var_dump,它會向我顯示一個包含兩個結果的數組。

我不想將列名硬編碼到我的函數中。我希望它是動態的。所以無論我要求什麼表或列,它都會把所有東西都放到我的對象中。

+0

你試過看PDO嗎? – Amber 2010-09-23 03:37:25

回答

1

一個Object Relational Mapper (ORM)可以給你很多你描述的功能(和更多)。看一看:

這裏是行走的代碼如下所示:

$book = BookQuery::create()->findPK(123); // retrieve a record from a database 
$book->setName('Don\'t be Hax0red!'); // modify. Don't worry about escaping 
$book->save(); // persist the modification to the database 

$books = BookQuery::create() // retrieve all books... 
    ->filterByPublishYear(2009) // ... published in 2009 
    ->orderByTitle()   // ... ordered by title 
    ->joinWith('Book.Author') // ... with their author 
    ->find(); 

foreach($books as $book) { 
    echo $book->getAuthor()->getFullName(); 
} 
0

嘗試

pg_fetch_object

閱讀文檔

例如

<?php 
$database = "test"; 
$db_conn = pg_connect ("host=localhost port=5432 dbname=$database"); 
if (!$db_conn): ?> 
    <H1>Failed connecting to postgres database <?php echo $database ?></H1> <?php 
    exit; 
endif; 

$ep = pg_query ($db_conn, "SELECT * FROM verlag ORDER BY autor"); 
$row = 0; // postgres needs a row counter other dbs might not 

while ($data = pg_fetch_object ($ep, $row)) { 
    echo $data->fname; 
    $row++; 
} 

?> 
+0

-1它的瘋狂,它有什麼不好,請突出顯示,這樣我也可以學習。 – 2010-09-23 04:00:40

+0

這似乎工作。我不得不從while循環中刪除$行,因爲我收到了一條錯誤消息。 – Keith 2010-09-23 04:02:42

+0

是的,請解釋爲什麼有人投了這個票? – Keith 2010-09-23 04:03:25

0

您需要通過結果來構建你自己的數組或對象,然後循環,增加當你去的時候,它們都是數組/對象。

有一些包含此功能的軟件包,如ezSQL