簡體   English   中英

從返回的SQL查詢中提取值

[英]extract values from a returned sql query

我正在使用PHP。 我有一個數據庫,我從中提取數據。 我現在有數據輸出到一個表。

我的願望是使用此表並分離數據以傳遞給單獨的變量,我是否應該如何傳遞給數組?

例如原始

Name          hours
Bob             4
Harry           6
Bob             2
Harry           5
Dave            1
Bob             2

返回並在表中

Bob             3
Harry           2
Dave            1

我想按照我的意願並按照行順序分別取每個值,所以我便有了變量

Bob = 3, Harry = 2, Dave = 1

並取值3,2,1

然后將其輸出,並將變量用於創建餅圖

這是我的SQL查詢

    $dbHandle = new PDO("mysql:host=$host;dbname=$dbName",$user,$pass);
    $query ="SELECT platform, count(*) FROM review GROUP BY platform";
    $sqlQuery = $query; // put your students table name
    echo $sqlQuery;  //helpful for debugging to see what SQL query has been created
    $statement = $dbHandle->prepare($sqlQuery); // prepare PDO statement
    $statement->execute();   // execute the PDO statement
    echo "<table border='1'>";
    while ($row = $statement->fetch()) {
    echo "<tr><td>" . $row[0] ."</td><td>". $row[1];}
    echo "</table>";
    $dbHandle = null;

您可以使用AS命名查詢中的SQL列,並使用ORDER BY對其進行排序: SELECT platform AS plat, count(platform) AS count FROM review GROUP BY platform ORDER BY count DESC

在獲取結果的代碼中,您可以選擇以關聯數組的形式獲取每一行:

while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {//this will fetch results and index them into the row array with column names:
    echo "<tr><td>" . $row['plat'] ."</td><td>". $row['count']."</td></tr>";
}

這可能是簡單的方法,但是請記住,以后可能要對它們進行不同的排序。 在獲得結果時也回顯結果可能是一個錯誤的設計。 更好的方法是將它們存儲在數組中,然后循環並回顯它。 所以這里是:

$results = $statement->fetchAll(PDO::FETCH_ASSOC);

//order the results the way you want here

echo "<table border='1'>";
//then echo them out:
foreach($results as $key => $result){
    echo "<tr><td>" . $result['plat'] ."</td><td>". $result['count']."</td></tr>";
}
echo "</table>";

總而言之,這是您的代碼示例:

$dbHandle = new PDO("mysql:host=$host;dbname=$dbName",$user,$pass);
$query ="SELECT platform AS plat, count(platform) AS count FROM review GROUP BY platform ORDER BY count DESC";
$sqlQuery = $query; // put your students table name
//echo $sqlQuery;  //helpful for debugging to see what SQL query has been created
$statement = $dbHandle->prepare($sqlQuery); // prepare PDO statement
$statement->execute();   // execute the PDO statement
$results = $statement->fetchAll(PDO::FETCH_ASSOC);//data is here, just draw the chart

//you can access the data in the array like this: 

foreach($results as $key => $value){//$value is one row of results
    echo '<some html you="need" for the piechart>'.$value['plat']/*name of the platform*/.'</some closing tag perhaps><another tag>'.$value['count'].'</closed>';
}
$dbHandle = null;

暫無
暫無

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

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