[英]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.