2017-04-12 106 views
0

我想用MySQL中的数据填充我的Datatable,但无法弄清楚如何去做。我希望能够将DataTable填充到页面,然后用户可以单击一行并将该行的数据用于用户将被重定向到的下一页。这是我到目前为止有:使用来自MySQL和PHP的数据填充DataTable

<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文件:

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

您初始化错误一。 – Irvin

+0

对不起,我更正了。 – Carbon

+0

选中此:https://github.com/pandeyz/Jquery-Datatable---Server-Side-with-Custom-Inline-Editing –

回答

1

使用数据表API,而不是

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)); 
+0

谢谢你的回答!我相信这也能起作用,但我想我只是通过将URL传递给PHP GET变量来传递数据的解决方案。 – Carbon