如何解析sql结果?

时间:2016-12-17 19:24:37

标签: javascript php mysql

结束我的悲伤。

我向此文件发出ajax请求。

我想从数据库中获取所有帖子。然后设计这些帖子的样式并将其显示给用户。

但我无法弄清楚如何从js解析这些。

namespace std

1 个答案:

答案 0 :(得分:0)

  

从你的帖子中,你听起来想要将从数据库事务中获得的一些数据发送到请求AJAX脚本,对吧?如果是这样的话;您可能必须执行所有常用的DB数据处理,并且(如果需要)在PHP文件中将它们构建为数组或对象。然后,使用json_encode()将结果数据编码为JSON,最后将JSON编码数据推送回请求的AJAX脚本。为了显示;这里(下面)是一个使用位& amp;的模拟示例。您发布的代码片段:

<?php

    // PERFORM SOME DATABASE TRANSACTIONS....
    $result    = $conn->query($sql);

    // IF YOU NEED TO BUILD-UP A SPECIAL DATA STRUCTURE TO MEET WITH 
    // THE NEEDS OF YOUR APP. YOU MIGHT DO THAT HERE.
    // WE CREATE AN ARBITRARY ARRAY: $payload TO HOLD THE ARBITRARY DATA...
    $payload   = [];

    // LOOP THROUGH THE RETURNED RESULT-SET / ROWS OF DATA
    while($row = $result->fetch_assoc())  {
        // WE PRETEND FOR NOW THAT WE NEED CERTAIN VALUES FOR THE APP
        // THAT WILL BE CONSUMED BY THE REQUESTING AJAX SCRIPT
        // SO WE BUILD IT HERE:
        $tempData       = [];     //<== TEMPORARY ARRAY TO HOLD A COLLECTION 
        $tempData[]     = $row['firs_name'];
        $tempData[]     = $row['last_name'];
        $tempData[]     = $row['address'];
        $tempData[]     = $row['email'];
        $tempData[]     = $row['avatar'];
        $tempData[]     = $row['telephone'];

        // NOW PUSH THE COLLECTION OF RELEVANT DATA GATHERED 
        // FROM THE ITERATION INTO THE PAYLOAD VARIABLE: $payload
        $payload[]      = $tempData;
    } 

    // OK: WE HAVE OUR PAYLOAD, READY TO BE SENT BACK AS JSON...
    // SO WE NOW ENCODE THE PAYLOAD TO JSON DATA STRUCTURE.
    $jsonData           = json_encode($payload);


    // THAT'S ALMOST IT....
    // THE NEXT THING WOULD BE TO SHIP THESE DATA TO THE REQUESTING SCRIPT
    // WHICH WE SHALL DO HERE WITH A SIMPLY die() STATEMENT LIKE SO:
    die($jsonData);