douweidao3882 2017-04-11 19:25
浏览 47
已采纳

使用来自MySQL和PHP的数据填充DataTable

I am trying to populate my Datatable with data from MySQL but can't figure out how to do so. I want to be able to populate the DataTable once directed to the page, then user can click on a row and use that row's data for the next page the user will be redirected to. This is what I have so far:

<table id="example" class="display" cellspacing="0" width="100%">
<thead>
    <tr>

        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
    </tr>

</thead>
<tfoot>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
    </tr> 
</tfoot>
<tbody>
    <tr>
        <td> Placeholder1</td>
        <td> Placeholder2</td>
        <td> Placeholder3</td>
    </tr>
    <tr>
        <td> Placeholder1</td>
        <td> Placeholder2</td>
        <td> Placeholder3</td>
    </tr>
    <tr>
        <td> Placeholder1</td>
        <td> Placeholder2</td>
        <td> Placeholder3</td>
    </tr>
</tbody>
</table>

<script>


$(document).ready(function() {
var table = $('#example').DataTable();

$('#example tbody').on('click', 'tr', function () {
    var data = table.row( this ).data();
    alert( 'You clicked on '+data[0]+'\'s row' );
} );
} );
</script>

PHP FILE:

<?php

include('connection.php');



 $sql = "SELECT ID, Name, Age, Gender FROM DBTABLE";


$response = mysqli_query($db, $sql);


if($response)
{
    echo '<table>';

   while($row = mysqli_fetch_array($response))
    {

       echo '<tr><td align="left">' .
            $row['Name'] . '</td><td align="left">' .
            $row['Age']  '</td><td align="left">' .
            $row['Gender'] . '</td><td align="left">';


       echo '</tr>';
    }

   echo '</table>';

  }
else
{
    echo "Couldn’t issue database query<br />";
    echo mysqli_error($db);
}






// Close connection to the database
mysqli_close($db);
?>

展开全部

  • 写回答

1条回答 默认 最新

  • dth62818 2017-04-11 21:49
    关注

    Use the dataTables API instead

    var table = $('#example').DataTable({
      ajax: {
        url: 'phpfile.php'
      },
      columns: [
        { data: 'Name' },
        { data: 'Age' },
        { data: 'Gender' }
      ]
    });
    

    phpfile.php

    ...
    $data = array();
    if ($response) {
      while($row = mysqli_fetch_assoc($response)) {
        $data[] = $row;
      }
    }
    echo json_encode(array('data' => $data));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部