In my Datatables grid, I load MySQL data with a server-side PHP script. I need to loop inside column. For example my datatables currently (select from tb order):
//product table
| id | Salesman
-----------------------------------------
| 1 | Arthur
| 2 | Richard
| 3 | Patrick
Since there is more than one product per order, I want to loop inside column to show all products from that order like this (INNER JOIN tb products x tb order):
| id | Salesman Products
-----------------------------------------
| 1 | Arthur | Link stabilizer |
| CV joint kits |
| Parke brake lever |
| 2 | Richard | Radiator hose |
| Park brake lever |
| 3 | Patrick | Radiator hose |
I tried to use while{} inside "render" function, but didn't work cause JS is client side. I tried ajax inside "render" function, but always give me an alert: DataTables warning: table id=user_data - Requested unknown parameter '0' for row 0, column 0.
JAVASCRIPT:
var dataTable = jQuery('#user_data').DataTable
({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
"columnDefs":[{
"targets":[1],
"render": function (data, type, row, meta) {
var dados=data;
$.ajax({
url: "list.php",
dataType:"json",
type: "POST",
data: {dados: dados},
success: function(data) {console.log(data);}
})
}
}],
});
//SERVER SIDE SCRIPT TO MAKE LOOP INSIDE COLUMN(list.php):
<?php
include("db.php");
$dados = $_POST['dados'];
$sql1="SELECT product FROM app_order WHERE order='$dados'";
$result1=$mysqli->query($sql1);
while($row1=mysqli_fetch_array($result1)){
$product=$row1['product']; }
echo json_encode(array($product));
?>
//fetch.php to build whole table:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query = "SELECT * FROM order ";
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[]= $row['order'];
$sub_array[] = $row['salesman'];
$sub_array[] = 'I need an array here';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>