We're back. Kind of. Clearing out the cobwebs. Much stuff broken. Much stuff coming. More details to come. So much spam.
1
Formatting data as a JSON table using PHP and MySQL?
Post Body

I am trying to generate a JSON formatted table using data from my database. When doing so, I get the error PHP Fatal error: Call to a member function fetch() on a non-object in G:\PleskVhosts\mywebsite.com\httpdocs\getData.php on line 23

(This is line 19 here)

I'm not sure why it's giving this error as I did something very similar on another page and it works pefectly fine. Here is my code.

<?

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


?>

Author
FrostyJesus

14 years old ยท 155k karma

Account strength 100%
Age
14 years
Total karma
155k
Comment karma
118k
Signals Verified email Verified flair
View profile
Profile refreshed 1 year ago Posts refreshed 1 year ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
10 years ago