2011-12-15 31 views
0

我想返回數據庫表中找到的所有內容的數組。該表只有2列:id和song_url。我想陣列看起來像這樣:需要幫助返回數據庫表中所有內容的數組PHP/PDO

Array { 
    1 => songurl1, 
    2 => songurl2, 
    3 => songurl3 
} 

的關鍵是每一行的ID和值是每一行的song_url。我爲此使用了PDO。

謝謝。

編輯(沒看到編輯按鈕:S):

這裏是我做這個當前代碼:

class Database { 

protected $connected = false; 
protected $dbh = null; 
public $test = array(); 

function __construct($host=null, $user=null, $pass=null, $db=null) { 
    if ($host && $user && $pass && $db) { 
     try { 
      $this->dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass); 
      $this->connected = true; 
     } catch (PDOException $e) { 
      echo "Could not connect to the database. Please contact an administrator."; 
      $this->connected = false; 
      exit(); 
     } 
    } else { 
     echo "No or not all variables are passed to the constructer. Contact an administrator."; 
     $this->connected = false; 
     exit(); 
    } 
} 

public function fetchAllSongs() { 
    $q = $this->dbh->query("SELECT * FROM song_directories"); 
    $result = $q->fetch(PDO::FETCH_ASSOC); 

    return $result; // this returns an array, yes, but only 1 row 

} 

} 

此外,在fetchAllSongs返回只顯示一行(當我使用print_r()),而不是所有的行。這是爲什麼?

+0

發佈你想要的東西而不顯示任何努力似乎是可疑的,就像你要求我們爲你做你的工作。我們通常期望人們嘗試自行解決問題,並且只有在問題被困在某些事物上時纔會發問。 – Herbert 2011-12-15 04:30:16

+0

是的,對不起,我編輯了我的問題。到目前爲止我還沒有嘗試過任何東西,但我懷疑我可能會嘗試保羅的回答。我沒有多少時間來處理這個問題。 – Alphaspida 2011-12-15 20:06:37

回答

0

您可以運行2個查詢(每列一個),然後使用array_combine創建所需的數組。

<?php 
/* 
$column_id  = // Get the ID column 
$column_song_url = // Get the song_url column 
*/ 

$result = array_combine($column_id, $column_song_url); 
?> 
+1

但是,這不是不必要的開銷嗎? – Nonym 2011-12-15 03:42:48

0

這個怎麼樣?:

$testArray = array(); 
for ($i = 0; $i<=count($rsArr)-1;$i++) { 
    $testArray[$rsArr[$i]->id] = $rsArr[$i]->song_url; 
} 

只是要注意:這裏的危險是,如果您有任何重複id值。

2

看看manual page for query上的例子。在foreach循環中創建你的數組:

$data[$row['id']] = $row['songurl']; 

不要使用2個查詢來完成這樣簡單的事情。

您編輯的代碼非常接近。只需將fetch更改爲fetchAll,然後根據需要重新排列陣列。