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
.