以 JSON 格式显示 SQL 结果并使用 Javascript 解析数据。

<?php

$pdo = new PDO("mysql:dbname=sample;host=localhost", "admin", "passwd");        

$statement = $pdo->prepare("SELECT first_name, last_name FROM accounts WHERE account_id='1'");

$statement->execute();

$results = $statement->fetchAll(PDO::FETCH_ASSOC);

$json = json_encode($results);

echo "$json";

?>

结果是


[{"first_name":"John","last_name":"Doe"}]

使用 javascript 的预期结果:


John Doe


侃侃无极
浏览 141回答 1
1回答

陪伴而非守候

作为评论中的 json 代码,您可以执行以下操作:var obj = JSON.parse('[{"first_name":"john","last_name":"doe"},{"first_name":"Jeen","last_name":"dra"},{"first_name":"Ad","last_name":"Does"},{"first_name":"Arin","last_name":"Gan"},{"first_name":"Jason","last_name":"Ford"},{"first_name":"Prince","last_name":"addar"},{"first_name":"Derek","last_name":"Frenzi"},{"first_name":"Jay","last_name":"dar"},{"first_name":"dam","last_name":"guly"},{"first_name":"nita","last_name":"Sa"}]');for (i=0 ; i<obj.length ; i++){&nbsp; &nbsp;document.getElementById("demo").innerHTML += obj[i].first_name + " " + obj[i].last_name + "<br>" ;}
打开App,查看更多内容
随时随地看视频慕课网APP