[英]Show query result in PHP
I have a query: 我有一个查询:
$string = "SELECT COUNT(id) as sponsered FROM `$database`.`$mem` where parent_id = 2 group by plan";
Which result in: 结果是:
sponsored plan
2 gold
1 silver
1 mitra
This result is shown when I run this query in MySQL. 当我在MySQL中运行此查询时,将显示此结果。
Now I want this result in PHP in an array data[] where 现在,我希望此结果在PHP中以数组data []其中
data[0] contains 2
data[1] contains 1
data[2] contains 1
I have tried this 我已经试过了
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
while($data = mysqli_fetch_assoc($res)) {
echo $data['sponsered'];
}
But it results in data['sponsered']
containing 211
但这会导致data['sponsered']
包含211
It would be better if this can be done without using any loop. 如果可以在不使用任何循环的情况下完成此操作会更好。
Inside the while loop assign the values to array. 在while循环内,将值分配给array。
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
$data = array();
while($result = mysqli_fetch_assoc($res)) {
$data[] = $result['sponsered'];
}
print_r($data);
Output: 输出:
data[0] contains 2 数据[0]包含2
data[1] contains 1 数据[1]包含1
data[2] contains 1 数据[2]包含1
Your display is correct you just need a separator so the data isn't all clumped. 您的显示是正确的,您只需要一个分隔符,这样数据就不会全部聚集在一起。 In a browser: 在浏览器中:
echo $data['sponsered'] . "<br>";
in your loop should do it, or command line, 在您的循环中应该做到这一点,或在命令行中
echo $data['sponsered'] . PHP_EOL;
should do it. 应该这样做。
As is it throws 2
, then 1
, then 1
which views as 211
. 照原样抛出2
,然后是1
,然后是1
,其视作211
。
Please refrain from passing data directly into query in a prepare statement, use ? or :
请避免在prepare语句中将数据直接传递到查询中,请使用? or :
? or :
as deemed necessary. ? or :
视需要而定。
Below is a sample code: 下面是一个示例代码:
<?php
$table_name = $table; //not recommended to pass table_name as variable, unless necessary.
$parent_id = 2;
$p = $plan;
$string = "SELECT COUNT(id) as sponsered FROM $table_name where parent_id = ? group by ?";
if ($stmt = $db->prepare($string))
{
$stmt->bind_param('is', $parent_id, $p);
$stmt->execute();
$stmt->bind_result($sponsored, $plan);
$stnt->store_result();
$html ='';
while ($stmt->fetch() !== FALSE)
{
// Do what you like with the variables here, i.e. $sponsored, $plan
$html .= "<table>
<th> Sponsored </th>
<th> Plan</th>
<tr>
<td>$sponsored</td>
<td>$plan</td>
</tr>
</table>";
}
else {
die("Query failed");
}
var_dump($html);
}
?>
NOTE: If your result from your question is just an HTML (table/column) , you don't need to do bind, you can just output the HTML formatted. 注意:如果您从问题中得到的结果只是一个HTML (表/列) ,则无需进行绑定,您只需输出格式化的HTML。
使用mysqli_fetch_array($result, MYSQLI_NUM)
将数据作为数字数组检索
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.