在PHP中显示查询结果

时间:2017-09-01 16:40:41

标签: php mysql resultset

我有一个问题:

$ docker-compose -f docker-compose.development.yml up
Removing zoho-grabber-db-development
Recreating 1b341fd7916e_1b341fd7916e_zoho-grabber-db-development

ERROR: for db  Cannot start service db: oci runtime error: container_linux.go:247: starting container process caused "exec: \"mysqld\": executable file not found in $PATH"
ERROR: Encountered errors while bringing up the project.

结果如下:

$string = "SELECT COUNT(id) as sponsered FROM `$database`.`$mem` where parent_id = 2 group by plan";

当我在MySQL中运行此查询时,会显示此结果。

现在我想在PHP数据[]中的这个结果

 sponsored plan
         2 gold
         1 silver
         1 mitra

我试过这个

  data[0] contains 2
  data[1] contains 1
  data[2] contains 1

但结果是$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']; } 包含data['sponsered']

如果不使用任何循环就可以做到这一点会更好。

4 个答案:

答案 0 :(得分:0)

在while循环中将值分配给数组。

$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);

输出:

data [0]包含2
数据[1]包含1
data [2]包含1

答案 1 :(得分:0)

您的显示是正确的,您只需要一个分隔符,这样数据就不会全部聚集在一起。在浏览器中:

echo $data['sponsered'] . "<br>";
循环中的

应该执行它,或命令行,

echo $data['sponsered'] . PHP_EOL;

应该这样做。

按原样抛出2,然后1,然后1投放211

答案 2 :(得分:0)

试试这个:

请不要在准备声明中直接将数据传递到查询中,必要时使用? or :

以下是示例代码:

<?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);
    }
?>

注意:如果您问题的结果只是一个HTML (表/列),那么您不需要进行绑定,只需输出格式化的HTML。

答案 3 :(得分:-2)

使用mysqli_fetch_array($result, MYSQLI_NUM)将数据作为数字数组

进行检索