【问题标题】:Creating a JSON-Array from data got by Select query from MySQL Database从 MySQL 数据库中的 Select 查询获得的数据创建 JSON 数组
【发布时间】:2016-06-15 11:54:50
【问题描述】:

我正在尝试将 SQL Select-Query 的结果转换为 DataTables 可读格式的 JSON 文件。

现在我将结果转换为这种形式:

{  
   "data":[  
      [  
         "pIdWrittenHere1232131231",
         "sNameWrittenHere",
         "lNameWrittenHere",
         "http://Some.pLogUrl.writtenHere.com/",
         "incentivWrittenHere",
         "https://someDetailsUrl.WrittenHere.com/
      ],
       [  
         "pId2WrittenHere1232131231",
         "sName2WrittenHere",
         "lName2WrittenHere",
         "http://Some.pLogUrl.writtenHere.com/",
         "incentiv2WrittenHere",
         "https://someDetailsUrl.WrittenHere.com/
      ]
    ]
}

这是我用来实际转换它们的 php:

<?php


                                        /* Array of database columns which should be read and sent back to DataTables. Use a space where
                                         * you want to insert a non-database field (for example a counter or static image)
                                         */
                                        $aColumns = array( 'pId', 'sName', 'lName', 'pLogUrl', 'incent', 'det_sUrl');

                                        /* Indexed column (used for fast and accurate table cardinality) */
                                        $sIndexColumn = "id";

                                        /* DB table to use */
                                        $sTable = "tableName_here";

                                        /* Database connection information */
                                        $gaSql['user']       = "userHere";
                                        $gaSql['password']   = "passHere";
                                        $gaSql['db']         = "dataBaseHEre";
                                        $gaSql['server']     = "serverHere";


                                        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                                         * If you just want to use the basic configuration for DataTables with PHP server-side, there is
                                         * no need to edit below this line
                                         */

                                        /* 
                                         * MySQL connection
                                         */
                                        $gaSql['link'] =  mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) or
                                            die( 'Could not open connection to server' );

                                        mysql_select_db( $gaSql['db'], $gaSql['link'] ) or 
                                            die( 'Could not select database '. $gaSql['db'] );


                                        /* 
                                         * Paging
                                         */
                                        $sLimit = "";
                                        if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
                                        {
                                            $sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
                                                mysql_real_escape_string( $_GET['iDisplayLength'] );
                                        }


                                        /*
                                         * Ordering
                                         */
                                        if ( isset( $_GET['iSortCol_0'] ) )
                                        {
                                            $sOrder = "ORDER BY  ";
                                            for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
                                            {
                                                if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
                                                {
                                                    $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                                                        ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
                                                }
                                            }

                                            $sOrder = substr_replace( $sOrder, "", -2 );
                                            if ( $sOrder == "ORDER BY" )
                                            {
                                                $sOrder = "";
                                            }
                                        }


                                        /* 
                                         * Filtering
                                         * NOTE this does not match the built-in DataTables filtering which does it
                                         * word by word on any field. It's possible to do here, but concerned about efficiency
                                         * on very large tables, and MySQL's regex functionality is very limited
                                         */
                                        $sWhere = "";
                                        if ( $_GET['sSearch'] != "" )
                                        {
                                            $sWhere = "WHERE (";
                                            for ( $i=0 ; $i<count($aColumns) ; $i++ )
                                            {
                                                $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
                                            }
                                            $sWhere = substr_replace( $sWhere, "", -3 );
                                            $sWhere .= ')';
                                        }

                                        /* Individual column filtering */
                                        for ( $i=0 ; $i<count($aColumns) ; $i++ )
                                        {
                                            if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
                                            {
                                                if ( $sWhere == "" )
                                                {
                                                    $sWhere = "WHERE ";
                                                }
                                                else
                                                {
                                                    $sWhere .= " AND ";
                                                }
                                                $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
                                            }
                                        }


                                        /*
                                         * SQL queries
                                         * Get data to display
                                         */
                                        $sQuery = "
                                            SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
                                            FROM   $sTable
                                            $sWhere
                                            $sOrder
                                            $sLimit
                                        ";
                                        $rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());

                                        /* Data set length after filtering */
                                        $sQuery = "
                                            SELECT FOUND_ROWS()
                                        ";
                                        $rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
                                        $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
                                        $iFilteredTotal = $aResultFilterTotal[0];

                                        /* Total data set length */
                                        $sQuery = "
                                            SELECT COUNT(".$sIndexColumn.")
                                            FROM   $sTable
                                        ";
                                        $rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
                                        $aResultTotal = mysql_fetch_array($rResultTotal);
                                        $iTotal = $aResultTotal[0];


                                        /*
                                         * Output
                                         */
                                        $output = array(

                                            "aaData" => array()
                                        );

                                        while ( $aRow = mysql_fetch_array( $rResult ) )
                                        {
                                            $row = array();
                                            for ( $i=0 ; $i<count($aColumns) ; $i++ )
                                            {
                                                if ( $aColumns[$i] == "version" )
                                                {
                                                    /* Special output formatting for 'version' column */
                                                    $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
                                                }
                                                else if ( $aColumns[$i] != ' ' )
                                                {
                                                    /* General output */
                                                    $row[] = $aRow[ $aColumns[$i] ];
                                                }
                                            }
                                            $output['aaData'][] = $row;
                                        }

                                        $output = str_replace("\\/", "/", $output);

                                        echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);


                                    ?>

我认为必须在 php 中更改某些内容,以便获得 Datatable 中的数据...

这是我的 JavaScript:

$(document).ready(function() {
    $('#oShopTable').DataTable( {
        "bProcessing": true,
        "bServerSide": true,
        "ajax": "AdminPage2.php"

    } );
} );

这是返回的,当我用这个var_dump($output['data'][0]);替换这个echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

array(6) { 
    [0]=> string(8) "pIdHere12312312" 
    [1]=> string(10) "sNameHere" 
    [2]=> string(17) "lNameHere" 
    [3]=> string(85) "https://somePLogUrlHere.com" 
    [4]=> string(22) "incentivHere" 
    [5]=> string(161) "someUrlHere" 
}

【问题讨论】:

    标签: php jquery mysql json datatable


    【解决方案1】:

    试试这样的:

    $query = "SELECT `id` AS `pId` FROM `table`";
    // ...
    $data = array('data' => mysql_fetch_assoc ($rResultFilterTotal));
    $jsonData = json_encode($data);
    

    编辑:

    <?php
    
    
    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array('pId', 'sName', 'lName', 'pLogUrl', 'incent', 'det_sUrl');
    $aColumnsLabel = array('incent' => 'incentiv', 'det_sUrl' => 'detailsUrl');
    
    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = "id";
    
    /* DB table to use */
    $sTable = "tableName_here";
    
    /* Database connection information */
    $gaSql['user'] = "userHere";
    $gaSql['password'] = "passHere";
    $gaSql['db'] = "dataBaseHEre";
    $gaSql['server'] = "serverHere";
    
    
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP server-side, there is
     * no need to edit below this line
     */
    
    /*
     * MySQL connection
     */
    $gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password']) or
    die('Could not open connection to server');
    
    mysql_select_db($gaSql['db'], $gaSql['link']) or
    die('Could not select database ' . $gaSql['db']);
    
    
    /*
     * Paging
     */
    $sLimit = "";
    if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
        $sLimit = "LIMIT " . mysql_real_escape_string($_GET['iDisplayStart']) . ", " .
            mysql_real_escape_string($_GET['iDisplayLength']);
    }
    
    
    /*
     * Ordering
     */
    if (isset($_GET['iSortCol_0'])) {
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
            if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
                                                            " . mysql_real_escape_string($_GET['sSortDir_' . $i]) . ", ";
            }
        }
    
        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY") {
            $sOrder = "";
        }
    }
    
    
    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    $sWhere = "";
    if ($_GET['sSearch'] != "") {
        $sWhere = "WHERE (";
        for ($i = 0; $i < count($aColumns); $i++) {
            $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
        }
        $sWhere = substr_replace($sWhere, "", -3);
        $sWhere .= ')';
    }
    
    /* Individual column filtering */
    for ($i = 0; $i < count($aColumns); $i++) {
        if ($_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
            if ($sWhere == "") {
                $sWhere = "WHERE ";
            } else {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
        }
    }
    
    
    /*
     * SQL queries
     * Get data to display
     */
    $sQuery = "
                                                SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . "
                                                FROM   $sTable
                                                $sWhere
                                                $sOrder
                                                $sLimit
                                            ";
    $rResult = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
    
    /* Data set length after filtering */
    $sQuery = "
                                                SELECT FOUND_ROWS()
                                            ";
    $rResultFilterTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
    $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
    $iFilteredTotal = $aResultFilterTotal[0];
    
    /* Total data set length */
    $sQuery = "
                                                SELECT COUNT(" . $sIndexColumn . ")
                                                FROM   $sTable
                                            ";
    $rResultTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
    $aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];
    
    
    /*
     * Output
     */
    $output = array(
        "data" => array()
    );
    
    $index = 0;
    while ($aRow = mysql_fetch_array($rResult)) {
        $row = array();
        for ($i = 0; $i < count($aColumns); $i++) {
            $key = isset($aColumnsLabel[$aColumns[$i]]) ? $aColumnsLabel[$aColumns[$i]] : $aColumns[$i];
            if ($aColumns[$i] == "version") {
                /* Special output formatting for 'version' column */
                $row[$key] = ($aRow[$aColumns[$i]] == "0") ? '-' : $aRow[$aColumns[$i]];
            } else if ($aColumns[$i] != ' ') {
                /* General output */
                $row[$key] = $aRow[$aColumns[$i]];
            }
        }
        $output['data'] = $row;
    }
    
    $output = str_replace("\\/", "/", $output);
    
    echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    
    
    ?>
    

    【讨论】:

    • 我的代码在哪里?任何想法?而且我不需要表中的 pId,我需要每行 6 列
    • 添加了另一个解决方案,如果有帮助,请告诉我。我遗漏了一些东西,请立即尝试我的最后一次编辑。
    • 它没有帮助..它仍然说“无效的 Jason 响应”虽然,当我测试回显的 json 时,它是有效的!我应该添加一个 javascript 来创建数据表吗?
    • 请用 json 结果编辑你的第一篇文章,使用 var_dump 而不是 echo,就像 var_dump(json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    • 您是指网页上的回声?好的。但是它仍然是一个数组数组。形式仍然和我上面开头发布的一样,只是“aaData”现在是“data”。抱歉,我不能发布真实数据,因为它不是私人的..
    【解决方案2】:

    所以..这是解决方案!

    这里是我希望显示 DataTable 的页面 (index.php) 的 HTML 代码:

    <div class="panel-body">
        <table id="oShopP" class="display">
            <thead>
                <tr>
                   <th>Price Id</th>
                   <th>Sync Name</th>
                   <th>Light Name</th>
                   <th>Price Logo Url</th>
                   <th>Incentiv</th>
                   <th>JTS URL</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                   <th>Price Id</th>
                   <th>Sync Name</th>
                   <th>Light Name</th>
                   <th>Price Logo Url</th>
                   <th>Incentiv</th>
                   <th>JTS URL</th>
                </tr>
            </tfoot>
        </table>
    </div>
    

    这里是 AdPage-data.php 的 php:

    <?php
    /* Database connection start */
    $servername = "localhost";
    $username = "usernameHere";
    $password = "passwordHere";
    $dbname = "dbNameHere";
    
    $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
    
    /* Database connection end */
    
    
    // storing  request (ie, get/post) global array to a variable  
    $requestData= $_REQUEST;
    
    
    $columns = array( 
    // datatable column index  => database column name
        0=> 'p_Id', 
        1=> 's_Name',
        2=> 'l_Name',
        3=> 'pLogo_Url',
        4=> 'incentivation',
        5=> 'det_jtsURL'
    );
    
    // getting total number records without any search
    $sql = "SELECT p_Id, s_Name, l_Name, pLogo_Url, incentivation, det_jtsURL";
    $sql.= " FROM tableNameHere";
    $query=mysqli_query($conn, $sql);
    $totalData = mysqli_num_rows($query);
    $totalFiltered = $totalData;  // when there is no search parameter then total number rows = total number filtered rows.
    
    
    $sql = "SELECT p_Id, s_Name, l_Name, pLogo_Url, incentivation, det_jtsURL";
    $sql.=" FROM tableNameHere WHERE 1=1";
    if( !empty($requestData['search']['value']) ) {   // if there is a search parameter, $requestData['search']['value'] contains search parameter
        $sql.=" AND ( p_Id LIKE '".$requestData['search']['value']."%' ";    
        $sql.=" OR s_Name LIKE '".$requestData['search']['value']."%' ";
        $sql.=" OR l_Name LIKE '".$requestData['search']['value']."%' ";
        $sql.=" OR pLogo_Url LIKE '".$requestData['search']['value']."%' ";
        $sql.=" OR incentivation LIKE '".$requestData['search']['value']."%' ";
        $sql.=" OR det_jtsURL LIKE '".$requestData['search']['value']."%' )";
    
    }
    
    $query=mysqli_query($conn, $sql);
    $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. 
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
    /* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc  */    
    $query=mysqli_query($conn, $sql);
    
    $data = array();
    while( $row=mysqli_fetch_array($query) ) {  // preparing an array
        $nestedData=array(); 
    
        $nestedData[] = $row["p_Id"];
        $nestedData[] = $row["s_Name"];
        $nestedData[] = $row["l_Name"];
        $nestedData[] = $row["pLogo_URL"];
        $nestedData[] = $row["incentivation"];
        $nestedData[] = $row["det_jtsURL"];
    
        $data[] = $nestedData;
    }
    
    
    
    $json_data = array(
                "draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
                "recordsTotal"    => intval( $totalData ),  // total number of records
                "recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
                "data"            => $data   // total data array
                );
    
    echo json_encode($json_data);  // send data as json format
    
    ?>
    

    这里是jquery:

    $(document).ready(function() {
        var dataTable = $('#oShopP').DataTable( {
            "processing": true,
            "serverSide": true,
            "ajax":{
                url :"AdPage-data.php", // json datasource
                type: "post"
            }
        });
    } );
    

    当然 index.php 和 AdPage-data.php 必须在同一个文件夹中,这样这段代码才能正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 2019-02-03
      • 2016-04-12
      相关资源
      最近更新 更多