我試圖傳遞一個數組,這是從PHP到JavaScript使用json_encode的mySQL PDO查詢的結果。從mySQL查詢返回的字符串上使用json_encode時出錯
但是,如果其中一個字段包含空格,或者如果我嘗試在字符串上使用數據庫函數(僅選擇第一個非空格部分),則該對象似乎不存在,並且我的代碼不會編譯。
以下是執行代碼:
<?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
這將導致錯誤 Uncaught SyntaxError: Unexpected token var
因爲該行var someNextStuff
自帶意外,顯然該對象被轉換成一個空字符串?
而且,下面的選擇會導致同樣的問題:
$sql = "SELECT id, firstNames, lastName, gender, idPersonFather, idPersonMother
FROM a_person";
用含有象「瑪利亞安娜塞西莉亞」,且列值firstNames。
然而SQL查詢直接在數據庫上工作(在phpmyadmin中)。
但是,如果我省略了select和數組中的firstNames
字段,則代碼工作正常。
這可能是什麼原因造成的?
感謝您的幫助..
編輯:
我現在發現,
SELECT id, substring_index(coalesce('Maria anna blah','?'), ' ', 1) as firstName, <rest of fields>
作品,但
SELECT id, substring_index(coalesce(firstNames,'?'), ' ', 1) as firstName, <rest of fields>
沒有。
所以它必須是一些與那場,我想..
看起來你正在混合使用PHP和JavaScript,而沒有用'<?php'和'?>'標籤將它們恰當地分開,這就是導致語法錯誤的原因... –
對不起,我忽略了分隔符例如 - 現在添加..如前所述,代碼確實編譯和工作正常,只要我離開包含空格的字段。 – Rusty75
呵呵,好吧,好吧,看起來你需要在<?php echo json_encode($ personArray)後面加分號。 ?>'在JavaScript中。 –