使用PHP和MySQL生成JSON格式的表

时间:2015-11-13 06:21:13

标签: php mysql json

我正在尝试使用数据库中的数据生成JSON格式的表。这样做时,我收到错误PHP Fatal error: Call to a member function fetch() on a non-object in G:\PleskVhosts\mywebsite.com\httpdocs\getData.php on line 23

我不确定为什么它会给出这个错误,因为我在另一个页面上做了非常类似的事情并且它的工作非常好。这是我的代码。

<?

$db = new PDO("mysql:host=".$servername.";dbname=".$dbname.";", $username, $password);

$query = $db->query("SELECT 'MAJOR' as 'Major' SUM(IF(MAJOR = 'Computer Science',1,0)) as CS, SUM(IF(MAJOR = 'Computer Information Systems',1,0)) as CIS, SUM(IF(MAJOR = 'Other',1,0)) as Other FROM ages");



$table = array();
$table['cols'] = array(
    array('label' => 'Major', 'type' => 'string'),
    array('label' => 'CS', 'type' => 'number'),
    array('label' => 'CIS', 'type' => 'number'),
    array('label' => 'Other', 'type' => 'number')
);

$rows = array();
while($r = $query->fetch()){
    $temp = array();
    $temp[] = array('v' => $r['Major']);
    $temp[] = array('v' => (int) $r['CS']);
    $temp[] = array('v' => (int) $r['CIS']);
    $temp[] = array('v' => (int) $r['Other']);

    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;

$jsonTable = json_encode($table);

echo $jsonTable;


?>

1 个答案:

答案 0 :(得分:0)

如果您认为这不是后退问题,以及错误报告问题,请运行以下内容。并将选择后面的刻度更改为单引号。看看你得到了什么。

使用以下内容作为模板,了解如何设置错误报告和try / catch块。

模式

create table basic_info2
(   id int auto_increment primary key,
    n_id int not null,
    name varchar(20) not null,
    date_released date not null,
    genres varchar(20) not null
);

insert basic_info2(n_id,name,date_released,genres) values (1,'a','2015-04-11','b');

PHP

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$servername = "host";
$username = "dbuser";
$password = "pwd";
$database = "dbname";

try {
    //Make your connection handler to your database
    $conn = new PDO("mysql:host=".$servername.";dbname=".$database, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

    $sql = "SELECT `N_ID`, `NAME`, `DATE_RELEASED`, `GENRES` FROM basic_info2 ORDER BY N_ID DESC LIMIT 10";
    $stmt = $conn->prepare($sql);
    //Execute the query
    $stmt->execute();
    $result = $stmt->fetchAll();
    //Fetch the results
    foreach ($result as $row) {
        echo '<p>'.$row['NAME'].'</p>';
    }

} catch(PDOException $e) {
    echo $e->getMessage();
    die();
}
?>

修改

关于你的评论如下,这就是你所拥有的

SELECT MAJOR as 'MAJOR'
SUM(IF(MAJOR = 'Computer Science',1,0)) as CS, 
SUM(IF(MAJOR = 'Computer Information Systems',1,0)) as CIS, 
SUM(IF(MAJOR = 'Other',1,0)) as Other 
FROM ages

这就是你所需要的(只是缺少逗号行1)

SELECT MAJOR as 'MAJOR',
SUM(IF(MAJOR = 'Computer Science',1,0)) as CS, 
SUM(IF(MAJOR = 'Computer Information Systems',1,0)) as CIS, 
SUM(IF(MAJOR = 'Other',1,0)) as Other 
FROM ages