I'm trying to read some information from a MySQL database using php and then pass the results to jquery and log them in the console.
To read from the database I use:
public function getQuestions(){
$query = 'SELECT * FROM Question';
$statement = $this->db->prepare($query);
$statement->execute();
$questions = [];
while($row = $statement->fetch()){
$questions[] = array(
'QuestionID' => $row['QuestionID'],
'Content' => $row['QuestionContent']
);
}
return $questions;
}
where $this->db
is a PDO object.
Then this method is called from
<?php
include_once 'classes/DatabaseAdapter.php';
$dba = new DatabaseAdapter();
echo $dba->getQuestions(); // Array to String conversion error.
And that is then called from jQuery with:
$.ajax({
url: 'questions.php',
method: 'post'
}).done(function(data){
console.log('done');
console.log(data);
});
The problem I'm having is when I encode the output as json in PHP with json_encode()
I get an empty string in the console and decode it in jQuery with JSON.parse()
. Then I try passing it without encoding and get a notice saying Array to String conversion in PHP line with echo
.
Try this way. You can adapt the code to your getQuestions()
function
Php code
//PDO connection
$host = "";
$user = "";
$dbname = "";
$pass = "";
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
//PDO Database query and Json encode
$STH = $DBH->prepare("SELECT * FROM Question");
$STH->execute();
$result = $STH->fetchAll();
$data = array();
$data['items'] = $result;
echo json_encode($data);
Jquery
//$.getJSON is a shorthand Ajax function
$.getJSON("questions.php", function(data) {
console.log(data);
$.each(data.items, function(i, value){
console.log(value.thecolumnnameinmysqltable);
})
})
In the Php im creating an array for the purpose that you can add extra data and retrieve it .eg
$data = array();
$data['data'] = array("one", "two", "three", "four");
$data['items'] = $result;
echo json_encode($data);
and to retrieve the $data['data'] array in Jquery you do
var one = data.data[0];
var two = data.data[1];
var three = data.data[2];
var four = data.data[3];
Getjson info -- http://api.jquery.com/jquery.getjson/
Try this.
echo json_encode($dba->getQuestions());
exit;