【发布时间】:2011-12-15 02:58:05
【问题描述】:
我想返回在数据库表中找到的所有内容的数组。该表只有 2 列:id 和 song_url。我希望数组看起来像这样:
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() 时),而不是所有行。这是为什么呢?
【问题讨论】:
-
不费吹灰之力就发布您想要的内容似乎很可疑,就像您要求我们为您完成工作一样。我们通常希望人们尝试自己解决问题,并且只有在他们真正遇到问题时才发布问题。
-
是的,抱歉,我编辑了我的问题。到目前为止,我还没有尝试过任何事情,但我怀疑我可以尝试 Paul 的回答。我没有太多时间在这方面做更多的工作。