实际上,我希望输出多于一行,并且只给我一行。这是我的代码,它仅返回一行。但是,当我运行相同的查询SELECT DISTINCTROW metal时,phpmyadmin中来自metals ORDER BY id DESC LIMIT 4的$ fsym给出了我想要的4行输出。
function readAnother()
{
$fsym = $_GET['fsym'];
echo $fsym . '<br>';
$query = "SELECT DISTINCTROW metal, $fsym from metals ORDER BY id DESC LIMIT 4";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1,$this->fsym);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->metal = $row['metal'];
$this->price_eur = $row[$fsym];
}
答案 0 :(得分:0)
最好使用以下功能:http://php.net/manual/ru/pdostatement.fetch.php 像这样:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$this->metal = $row['metal'];
$this->price_eur = $row[$fsym];
}
如果您想使用fetchAll
,请像这样使用它:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$this->metal = $row['metal'];
$this->price_eur = $row[$fsym];
}
答案 1 :(得分:0)
根据对评论的讨论: 使用fetchall
您可以尝试以下代码
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$this->metal = $row['metal']; // by this it will add the last 4th record metal value in the variable
$this->price_eur = $row[$fsym];
}
我建议,如果要使用所有“金属”行,请使用适当的数组
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$finalArray = [];
foreach ($rows as $row) {
$finalArray[] = ['metal' => $row['metal'], 'price_eur'=> $row[$fsym]]
}
print_r($finalArray);