I am trying to pass an array which is the result of a mySQL PDO query from php to javascript using json_encode.
However if one of the fields contains spaces, or, if I try to use a database function on the string (to select only the first non-space part), the object seems to be nonexistent, and my code does not compile.
Following is the executed code:
<?php
$sql = "SELECT id, substring_index(firstNames, ' ', 1) as firstName, lastName, gender, idPersonFather, idPersonMother
FROM a_person";
$result = $db->query($sql);
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$personArray[$row['id']] = Array( 'firstName' => $row['firstName']
, 'lastName' => $row['lastName']
, 'gender' => $row['gender']
, 'idFather' => $row['idPersonFather']
, 'idMother' => $row['idPersonMother']);
}
?>
<html>
...
<script type="text/javascript" src="js/includes/grid_classes.js">
var personArray=<?php echo json_encode($personArray); ?>//get php aray
var someNextStuff
...etc
This will result in the error
Uncaught SyntaxError: Unexpected token var
because the line var someNextStuff comes unexpected, apparently the object is translated into an empty string?
Also, the following select causes the same problem:
$sql = "SELECT id, firstNames, lastName, gender, idPersonFather, idPersonMother
FROM a_person";
with firstNames containing values like 'Maria Anna Cecilia', and NULLs.
The SQL queries work on the database directly however (in phpmyadmin).
However, if I leave out the firstNames field from the select and the array, the code is working correctly.
What could be causing this?
thanks for your help..
Edit:
I now found that
SELECT id, substring_index(coalesce('Maria anna blah','?'), ' ', 1) as firstName, <rest of fields>
works, but
SELECT id, substring_index(coalesce(firstNames,'?'), ' ', 1) as firstName, <rest of fields>
does not.
So it has to be something with that field, I guess..
<?phpand?>tags, which is what's causing that syntax error...<?php echo json_encode($personArray); ?>in the JavaScript.json_encodeis naturally empty. You should probably check$result === falseand in that case output the error message in$db->errorInfo()