简体   繁体   English

从MySQL数据库中的Select查询获得的数据创建JSON-Array

[英]Creating a JSON-Array from data got by Select query from MySQL Database

I am trying to transform the result of an SQL Select-Query, to a JSON-File in a format readable by DataTables. 我正在尝试将SQL Select-Query的结果转换为DataTables可读格式的JSON-File。

Now I am getting the results transformed to this form: 现在,我将结果转换为以下形式:

{  
   "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/
      ]
    ]
}

Here is the php I am using to transform them actually: 这是我实际上用来转换它们的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);


                                    ?>

I thnik something must be changed in the php, so that I get the Data in the Datatable... 我认为必须在php中进行一些更改,以便将数据保存到数据表中。

Here is my JavaScript: 这是我的JavaScript:

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

    } );
} );

Here is the returned, when I replace this echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); 这是返回值,当我替换此echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); with this var_dump($output['data'][0]); 与此var_dump($output['data'][0]);

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" 
}

Try something like that: 尝试这样的事情:

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

Edit: 编辑:

<?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);


?>

So.. Here is the solution for that! 所以..这是解决方案!

Here the HTML-Code of the page (index.php) where I want the DataTable displayed: 这是我要在其中显示数据表的页面(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>

Here the php of AdPage-data.php: 这是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

?>

And here the jquery: 而这里的jQuery:

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

of course index.php and AdPage-data.php must be in the same folder, so that exactly this code works. 当然index.php和AdPage-data.php必须位于同一文件夹中,以便此代码可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM