簡體   English   中英

在PHP中獲取多行

[英]Fetch more than one row in php

實際上,我希望輸出多於一行,並且只給我一行。 這是我的代碼,它僅返回一行。 但是,當我運行相同的查詢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];

}

最好使用以下功能: 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];
}

根據評論的討論:使用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];
}

我建議如果要使用所有行“ metal”,請使用適當的數組

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$finalArray = [];
foreach ($rows as $row) {
    $finalArray[] = ['metal' => $row['metal'], 'price_eur'=> $row[$fsym]]

}
print_r($finalArray);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM