我想返回在数据库表中找到的所有内容的数组。该表只有两列: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()时),而不是所有行。这是为什么?
最佳答案
查看manual page for query上的示例。在foreach循环中,创建数组:
$data[$row['id']] = $row['songurl'];
不要对这样简单的事情使用2个查询。
您编辑的代码非常接近。只需将
fetch
更改为fetchAll
,然后根据需要重新排列数组即可。关于php - 需要帮助,以返回数据库PHP/PDO表中所有内容的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8514594/