我正在尝试使用数据库中的数据生成一个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;
?>
如果您认为这不是一个回溯问题,也不是一个错误报告问题,那么运行以下程序。并将选择反勾号更改为单引号。看看你得到了什么。
使用下面的模板了解如何设置错误报告和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