我设置了一个MySQL数据库($ database),其中包含一个表(“gigdata”)和列名如下:
每个列名称下面都有几行测试数据。我已经使用PHP的mysqli类成功连接到数据库,如下所示。
到目前为止,我已经写了这个PHP:
//Connect to database
$conn = new mysqli(localhost, $username, $password, $database);
//Check connection
if ($conn->connect_error) {
die("Failed to connect to MySQL: " . $conn->connect_error);
}
echo "<p>Connected to database</p>";
//Select data from database
$sql = "SELECT id, clientname, day, month, year, postcode, status, entered FROM gigdata";
$result = mysqli_query($conn, $sql);
//Create an empty array
$gigarray = array();
//Check data exists, if YES store in array
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
foreach ($row as $r) {
array_push($gigarray, $r);
}
}
} else {
echo "0 results";
}
然后我将JSON字符串回显到Javascript中,这很好用:
var gigdata = <?php echo json_encode($gigarray) ?>;
问题
我的目标是调整原始PHP,以便JSON最终格式化为:
希望这是有道理的,并且事先感谢。