I am doing a server-side pagination
this is my script,
$(document).ready(function() {
$('#dataTable').DataTable( {
'pagingType': 'full_numbers',
'paging' : true,
'responsive': true,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
ajax: {
url: "<?php echo $this->Url->build(['action' => 'tableview']); ?>"
},
columns: [
{ data: "id" },
{ data: "product_name" },
{ data: "unit" },
{ data: "price" },
{ data: "expiry_date" },
{ data: "stock"}
]
} );
});
and here is the query for the retrieval of data from the MySQL db and converting them into JSON
## Read value
$requestData = $this->request->getData();
$row = $requestData['start'];
$rowperpage = $requestData['length'];
$columnIndex = $requestData['order'][0]['column']; // Column index
$columnName = $requestData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $requestData['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = "";
if($searchValue != ''){
$searchQuery = " and (product_name like '%".$searchValue."%' or
id like '%".$searchValue."%' or
expiry_date like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from products");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from products WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from products WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$nested[] = array(
"id"=>$row['id'],
"product_name"=>$row['product_name'],
"unit"=>$row['unit'],
"price"=>$row['price'],
"expiry_date"=>$row['expiry_date'],
"stock"=>$row['stock']
);
}
$data = $nested;
## Response
$response = array(
"draw" => ($requestData['draw']),
"TotalRecords" => intval($totalRecords),
"TotalDisplayRecords" => intval($totalRecordwithFilter),
"Data" => $data
);
echo json_encode($response);
I am having a result of a JSON but it has a null string/value at the end making my JSON not valid.
ive tried removing the null and it makes the JSON valid. I want to know what causes the null or how can I remove it
This is how i view the result from php.
final String uri =
'My PHP FILE';
Future<List<Dbjobs>> dbgetdbusers() async {
var response = await http.get(uri);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<Dbjobs> dbusers = items.map<Dbjobs>((json) {
return Dbjobs.fromJson(json);
}).toList();
print(dbusers);
return dbusers;
} else {
throw Exception('Failed to load data.');
}
}
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Dbjobs>>(
future: dbgetdbusers(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView(
children: snapshot.data
.map((data) => Column(
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => JobDetails()));
},
child: Column(
children: <Widget>[
Container(
color: Colors.grey,
child: Column(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: Text(
data.dateCreated,
style: TextStyle(fontSize: 30.0),
),
),
My Login Php
<?php
session_start();
include 'testConz.php';
$username = $_POST['Username'];
$password =md5($_POST['Password']);
$Consult = $connect -> query("SELECT * FROM tuser_ppim WHERE LoginName = '$username' and Password = '$password' ");
$Result = array();
while ($extractData=$Consult->fetch_assoc()) {
$Result[] = $extractData;
}
$ID = $Result['0']['ID'];
$_SESSION['$Consult'] = $Result;
echo json_encode($Result);
?>
>
This php file works with flutter, there are results based on the query.
<?php
session_start();
include 'testConz.php';
$Consult1=$connect->query("
SELECT * FROM tjob WHERE AssignedTo = '6';
");
$Outcome1 = array();
while ($extractData=$Consult1->fetch_assoc()) {
$Outcome1[] = $extractData;
}
echo json_encode($Outcome1);
?>
>
This one makes my screen loads with no result. any ideas?
<?php
session_start();
include 'testConz.php';
$userDetails = $_SESSION['$Consult'];
$SesID = $userDetails['0']['ID'];
$Consult1=$connect->query("
SELECT * FROM tjob WHERE AssignedTo = ".$SesID.";
");
$Outcome1 = array();
while ($extractData=$Consult1->fetch_assoc()) {
$Outcome1[] = $extractData;
}
echo json_encode($Outcome1);
echo json_encode($userDetails);
?>
>
BTW both produces the number for AssignedTo is equal 6
AND
Both produces the same result when in browser. but when it is in flutter screen the other one has no result.
Thank you!
i am working in codeigniter and i need to show a list of destinations as row in datatables, like UK as Parent and London as Child destination.
i need to show them in datatable, i have created array of both parent and child data, but i am not able to understand, how to show them in datatable properly as each child destination row below their parent row.
something like wordpress parent and child category.
here is what i did as of now.
here is my controller
public function fetch_destinations(){
// POST data
$postData = $this->input->post();
// Get data
$data = $this->tourismo->fetch_dest_nested($postData);
echo json_encode($data);
}
this is my model
function fetch_dest_nested($postData=null)
{
$response = array();
## Read value
$draw = $postData['draw'];
$start = $postData['start'];
$rowperpage = $postData['length']; // Rows display per page
$columnIndex = $postData['order'][0]['column']; // Column index
$columnName = $postData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $postData['order'][0]['dir']; // asc or desc
$searchValue = $postData['search']['value']; // Search value
## Search
$search_arr = array();
$searchQuery = "";
if($searchValue != ''){
$search_arr[] = " (name like '%".$searchValue."%' ) ";
}
if(count($search_arr) > 0){
$searchQuery = implode(" and ",$search_arr);
}
## Total number of records without filtering
$this->db->set_dbprefix('');
$this->db->select('count(*) as allcount');
$records = $this->db->get('destinations')->result();
$totalRecords = $records[0]->allcount;
## Total number of record with filtering
$this->db->select('count(*) as allcount');
if($searchQuery != '')
$this->db->where($searchQuery);
$records = $this->db->get('destinations')->result();
$totalRecordwithFilter = $records[0]->allcount;
//fetch records
$this->db->select("*");
if($searchQuery != '')
$this->db->where($searchQuery);
$this->db->where('level', 1);
$this->db->order_by($columnName, $columnSortOrder);
$this->db->limit($rowperpage, $start);
$this->db->from("destinations");
$q = $this->db->get();
$final = array();
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$this->db->select("*");
$this->db->from("destinations");
$this->db->where("parentid", $row->id);
$q = $this->db->get();
if ($q->num_rows() > 0) {
$row->children = $q->result();
}
array_push($final, $row);
}
}
$data = array();
foreach($final as $parentdest){
$data[] = array(
"id"=>$parentdest->id,
"name"=>$parentdest->name,
"slug"=>$parentdest->slug
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
return $response;
}
this is my view
<table class="apitable table dt-table" id="destlist_table">
<thead>
<th>
Destination Id</th>
<th>Destination Name</th>
<th>Destination Slug</th>
</thead>
</table>
here is my jquery code for ajax request
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<!-- Script -->
<script type="text/javascript">
$(document).ready(function(){
var destlistDataTable = $('#destlist_table').DataTable({
'bDestroy': true,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
"searching": true,
"pageLength": 10,
"order":[[0,'desc']],
'ajax': {
'url':'<?php echo admin_url('tourismo/tourismo/fetch_destinations'); ?>',
'data': function(data){
}
},
'columns': [
{ data: 'id' },
{ data: 'name' },
{ data: 'slug' },
]
});
});
what i want is every child destination row should be just below its Parent destination row, i am just not able to understand how to work with this loop here.
this is the reference for what i want
I have a SQL view in phpmyadmin which has a is used to populate data in a table created using jquery jtable. The issue is quite bizarre as only one column's data which is being pulled by the view isn't being displayed and all of the others are being displayed without an issue. There is also no issue when I edit the fields and I can see the changes I made in phpmyadmin. How do I get the Successful column to display ? All help is greatly appreciated.
Screenshot of the table
js which handles creation of the table
function getLessonsLearnedResponseChildTable(ContainerID) {
var table = {
title: '',
width: '5%',
sorting: false,
edit: false,
create: false,
display: function(data) {
//create an image to be used to open child table
var $img = $('<img src="' + config.base_url + 'assets/images/expand_row-small.png" title="View Responses" style="height:30px;width:30px;cursor:pointer;" height="30" width="30"/>');
$img.click(function() {
$('#' + ContainerID).jtable('openChildTable',
$img.closest('tr'),
{
title: data.record.event,// + ' - Response Plans'
actions: {
listAction: config.base_url + "data_fetch/responses/" + data.record.risk_id,
deleteAction: config.base_url + 'data_fetch/delete_response/',
updateAction: config.base_url + 'data_fetch/edit_response/'
},
messages: defaultResponseMessages,
fields: LessonsLearnedResponseFields
}, function(data) {//opened handler
data.childTable.jtable('load');
});
});
//return image to show on row
return $img;
}
};
return table;
}
Controller method for the listAction:
function responses($risk_id = null, $offset = 0, $limit = 100, $order_by = 'response_id', $direction = 'ASC') {
$confirm_member = $this->User_model->confirm_member(true, false);
if (!$confirm_member['success']) {
$this->print_jtable_error(self::ERROR_NOT_LOGGED_IN);
return;
}
$user_id = $_SESSION['user_id'];
$this->load->model('Response_model');
$responses = $this->Response_model->get_all($risk_id, $user_id, $limit, $offset, $order_by, $direction);
if ($responses == false) {
$this->print_jtable_error(self::ERROR_NO_ACCESS_PERMISSION);
return;
} else {
return $this->print_jtable_result($responses);
}
}
get_all method in Response Model
/*
* Retrieves all responses associated with the risk
*/
public function get_all($risk_id, $user_id, $limit = null, $offset = 0, $order_by = null, $direction = 'ASC') {
//load risk model to check if user can read from project
$this->load->model('Risk_model');
if ($this->Risk_model->initialize($risk_id, $user_id) == false) {
return false;
}
if ($limit !== null && $limit != 0) {
$this->db->limit($limit, $offset);
}
if ($order_by !== null) {
$this->db->order_by($order_by, $direction);
}
$query = $this->db->select('SQL_CALC_FOUND_ROWS *', false)->from('view_responses')->where('risk_id', $risk_id)->get();
$data = $query->result_array();
$this->load->model('Task_model');
foreach ($data as &$response)
$response['WBS'] = $this->Task_model->normalize_WBS($response['WBS']);
$data['num_rows'] = $this->db->
query('SELECT FOUND_ROWS()', false)->row(0)->{'FOUND_ROWS()'};
return $data;
}
Screenshot of the sql view
successful is received but not displayed
http://imgur.com/MqCVAGm
I've been able to solve the problem. It was an issue with spelling. I had a missing c in successful coming from the SQL view and now its working fine.
I am trying to use json encode for the first time and need some insight to what I am doing wrong.
It should look like this:
{ teams : [ ["2147483647", "9"],["2147483647", "6"],["2147483647", "4"],["11", "2147483647"],["5", "2147483647"],["12", "8"],["10", "3"],["2147483647", "7"], ], results : [ [ [[0, 1],[0, 1],[0, 1],[1, 0],[1, 0],[0, 0],[0, 0],[0, 1],], [[0, 0],[0, 0],[0, 0],[0, 0],], [[0, 0],[0, 0],], [[0, 0],[0, 0]] ] ] }
But the data being returned looks like this:-
{"teams":[["2147483647","10","5","12","11","2147483647","2147483647","2147483647"],["7","3","2147483647","8","2147483647","4","6","9"]],"results":[["0","0","0","0","0","0","0","0"],["0","0","0","0","0","0","0","0"]]}
Code:
public function getAutoCompleteData($tournID, $db)
{
$max = $this->max($tournID);
$one = $this->tourn_info("1on1", $tournID);
$total_matches = $max;
$after_matches = $max / 2;
$matches = $db->query($this->select("*", "matches", "leagueID='{$tournID}' AND league='tourn'"));
while ($row = $db->fetchAssoc($matches)) {
$clan1 = $this->getname($row['clan1'], $tournID, "tourn", $ac = NULL, 1, 1, $wc2 = 0);
$clan2 = $this->getname($row['clan2'], $tournID, "tourn", $ac = NULL, 1, 1, $wc2 = 1);
if ($row['matchno'] <= $after_matches) {
$clan_one[] = $row['clan1'];
$clan_two[] = $row['clan2'];
$score_one[] = $row['score1'];
$score_two[] = $row['score2'];
}
}
$data = array(
'teams' => array(
$clan_one,
$clan_two
),
'results' => array(
$score_one,
$score_two
)
);
return $data;
}
Where it shows teams, it should close the bracket ] every two teams?
Hope someone can help.
Not saying this will fix your problem, but it may help you to understand PHP.
class mustBeAClass{
protected function max($tnid){
// must have this function - can be public for outside method use
}
protected function tourn_info($typ, $tnid){
// must have this function - can be public for outside method use
}
protected function getname($arg0, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6 = 0){
/* must have this function - can be public for outside method use
notice that $arg6 is how you assign default to arguments */
}
public function getAutoCompleteData($tournID, $db){
$db->open();
$max = $this->max($tournID); $one = $this->tourn_info("1on1", $tournID);
// what is the point of this ---->>>> $total_matches = $max;
$after_matches = $max / 2;
// notice query issue below
$matches = $db->query("SELECT * FROM matches WHERE leagueID ='$tournID' && league='tourn'"));
// while loop has problems
if($matches->num_rows < 1){
die('You have no matches');
}
else{
while($row = $db->fetch_assoc()){
$clan1 = $this->getname($row['clan1'], $tournID, 'tourn', null, 1, 1, 0);
$clan2 = $this->getname($row['clan2'], $tournID, 'tourn', null, 1, 1, 1);
if($row['matchno'] <= $after_matches) {
$clan_one[] = $row['clan1'];
$clan_two[] = $row['clan2'];
$score_one[] = $row['score1'];
$score_two[] = $row['score2'];
}
}
$data = array(
'teams' => array($clan_one, $clan_two),
'results' => array($score_one, $score_two)
);
}
$matches->free(); $db->close();
return $data;
}
}
$cls = new mustBeAClass;
echo json_encode($cls->getAutoCompleteData($tournId, $db));
Of course use the correct values for $tournId and your new mysqli(/*args*/) for $db.