PHP not deleting and inserting data right - php

How this code works is every time a user visits the page, i scrape all of the data from the table and pass it through the below posts. If the user hasn't accessed that page before and the database is empty with their cookie_id, then it inserts the content, if it is found then it deletes the content from the database and inserts it again. The problem I am having though is that when the deletion occurs it deletes everything and seems to insert one value from $data1 instead of all the data from $data. Any ideas as to why this is happening?
Backend:
$cookie_id = $this->input->cookie("session_id");
$selected_size = $this->input->post('selected_size');
$product_id = $this->input->post('product_id');
$product_name = $this->input->post('product_name');
$product_color = $this->input->post('product_color');
$q1 = $this->db->query("SELECT * FROM default_cart_temp
WHERE cookie_id = '$cookie_id'
AND is_paid = 'No'");
if ($q1->num_rows() > 0) {
$this->db->where('cookie_id', $cookie_id);
$this->db->delete('default_cart_temp');
foreach($product_id as $key => $value) {
$data1 = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data1);
echo json_encode(array('success' => true));
} else {
foreach($product_id as $key => $value) {
$data = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data);
}
Frontend:
selected_size = $('.selected_size1').text();
arr1 = selected_size.split(".");
ss1 = arr1.slice(0, -1);
product_id = $('.product_id1').text();
arr2 = product_id.split(".");
ss2 = arr2.slice(0, -1);
product_name = $('.product_name1').text();
arr3 = product_name.split(".");
ss3 = arr3.slice(0, -1);
product_color = $('.product_color1').text();
arr4 = product_color.split(".");
ss4 = arr4.slice(0, -1);
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/products/products/new_instance",
data: { selected_size: ss1, product_id: ss2, product_name: ss3, product_color: ss4 },
json: {success: true},
success: function(data) {
if(data.success == true) {
alert("True");
}
}
});

In every foreach loop execution you are overriding $data and $data1 variables. You have to change them to arrays and add data like this $data[] = $subArray.

Related

How to Remove the Null Value at the End of a JSON

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

how to show array of parent and child Data as row in datatables

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

how multi update data on codeigniter

how to take the auto increment value to post.
here I insert two tables successfully, I create a condition after insertion, then update the data.
I have two tables, the first 'service' table and the second table 'customer_address'
customer_address table, has id_address as autoincrement.
when inserting data into two tables, I want to get the value id_address in the customer_address table. to be updated to the 'service' table.
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
//'id_alamat' => this autoincrement
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db-> select('id_alamat')-> from('customer_address')->where('id_kota', $kot)->get()-> result();
foreach($sheet as $value) {
$hsl = array(
'id_muat' => $value - > id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}
when I updated the 'service' table I updated everything. how to update based on the data input only?
You must send id_alamat from view to your controller and make a unique code not just using autoincrement.
for example:
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
'id_alamat' => $row['id_alamat'],
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db->select('id_alamat')->from('customer_address')->where('id_kota', $kot)->get()-> result();
//change $sheet to $isi
foreach($isi as $value) {
$hsl = array(
'id_muat' => $value->id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}

Array to string conversion - Laravel 5.6 Error

I am trying to update values in the DB using values from a JSON file:
Code:
$jsonData = file_get_contents($jsonFile);
$data = json_decode($jsonData, true);
//check if hospital exist
$name = explode(' ',trim($data['organisationUnits']['organisationUnit']['name']));
// echo $name[0];
$query = Hospital::where('h_name', 'LIKE' , '%' . $data['organisationUnits']['organisationUnit']['name'] . '%')->first();
if($query){
// echo "\n yupo";
$h_id = $query->id;
$h_slug = $query->h_slug;
$nr_orgUnit = $query->nr_orgUnit;
// echo $nr_orgUnit;
$updateHospital = Hospital::find($h_id);
$updateHospital->h_name = $data["organisationUnits"]["organisationUnit"]["name"];
$updateHospital->h_short_name = $data["organisationUnits"]["organisationUnit"]["shortName"];
$updateHospital->h_code = $data["organisationUnits"]["organisationUnit"]["code"];
$updateHospital->h_opening_date = $data["organisationUnits"]["organisationUnit"]["openingDate"];
$updateHospital->h_closed_date = $data["organisationUnits"]["organisationUnit"]["closedDate"];
$updateHospital->h_active = $data["organisationUnits"]["organisationUnit"]["active"];
$updateHospital->h_comment = $data["organisationUnits"]["organisationUnit"]["comment"];
$updateHospital->h_geo_code = $data["organisationUnits"]["organisationUnit"]["geoCode"];
$updateHospital->h_last_updated = $data["organisationUnits"]["organisationUnit"]["lastUpdated"];
$updateHospital->save();
} else {
// echo 'error';
}
JSON DATA:
{"organisationUnits":{
"organisationUnit":{
"id":"01",
"uuid":{
},
"name":"Isagehe Dispensary",
"shortName":"Isagehe Dispensary ",
"code":"17-04-0118",
"openingDate":"1990-01-01",
"closedDate":{
},
"active":"true",
"comment":{
},
"geoCode":{
},
"lastUpdated":{
}
}
}
}
when i try to run the code, i get the following error:
Array to string conversion (SQL: update `ag_hospitals` set `h_closed_date` = , `h_active` = true, `h_comment` = , `h_geo_code` = , `h_last_updated` = where `id` = 41)"
where might i be wrong?
Note i have also tried updating the following way:
$updateHospital = Hospital::where('id', $h_id)->update([
'h_name' => $data['organisationUnits']['organisationUnit']['name'],
'h_short_name' => $data['organisationUnits']['organisationUnit']['shortName'],
'h_code' => $data['organisationUnits']['organisationUnit']['code'],
'h_opening_date' => $data['organisationUnits']['organisationUnit']['openingDate'],
'h_closed_date' => $data['organisationUnits']['organisationUnit']['closedDate'],
'h_active' => $data['organisationUnits']['organisationUnit']['active'],
'h_comment' => $data['organisationUnits']['organisationUnit']['comment'],
'h_geo_code' => $data['organisationUnits']['organisationUnit']['geoCode'],
'h_last_updated' => $data['organisationUnits']['organisationUnit']['lastUpdated']
]);
You need to define that Attribute in Model that store that JSON Data as Array.
Example:
protected $casts = [
'column_name' => 'array'
];

Using render() value does not update when color box open second time

I'm posting value using color box from view to controller. First time it works perfectly fine but when I reopen the color box it POST the old value to the new.
This is my color box code:
$('#equipmentPopup').colorbox({
ajax: true,
width: "620px",
height: "450px",
href: showEquipment,
data: {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
});
This is my action code:
public function actionShowEquipment()
{
$this->layout = "//layouts/popup";
$equipmentConflicts = '';
$briefingId = $_POST['briefingId'];
$briefingDate = $_POST['briefingDate'];
$briefingEndDate = isset($_POST['briefingEndDate']) ? $_POST['briefingEndDate'] : '';
$serializeBriefingEquipments = isset($_POST['briefingEquipments']) ? $_POST['briefingEquipments'] : '';
$equipment = CHtml::listData(Equipment::model()->findAll(), 'id', 'name');
$briefingCenter = BriefingCenter::model()->findByPk(Yii::app()->user->currentBriefingCenterId);
if ($briefingId) {
$briefingEquipmentArr = BriefingEquipment::model()->findAll('briefing_id = :bId', array(':bId' => $briefingId));
if (!$briefingEquipmentArr) {
$briefingEquipmentArr[] = new BriefingEquipment();
}
} else if ($serializeBriefingEquipments) {
$serializeBriefingEquipments = unserialize($serializeBriefingEquipments);
}
$briefing = Briefing::model()->findByPk($briefingId);
if (!empty($briefing->scheduled_date) && !empty($briefing->scheduled_end_date)) {
$minDate = $briefing->scheduled_date;
$maxDate = $briefing->scheduled_end_date;
} else {
$minDate = $briefingDate;
$maxDate = $briefingEndDate;
}
echo $this->render('edit/equipment', array(
'briefing' => array(
'briefingId' => $briefingId,
'briefingDate' => $briefingDate,
'briefingEndDate' => $briefingEndDate,
),
'minDate' => strtotime($minDate),
'maxDate' => strtotime($maxDate),
'briefingEquipmentArr' => $briefingEquipmentArr,
'equipments' => $equipment,
'briefingCenter' => $briefingCenter,
'serializeBriefingEquipments' => $serializeBriefingEquipments,
'dateFormat' => Yii::app()->user->currentBriefingCenterDateFormat,
));
}
Your code does not work for me. I see there is no passed data by colorbox, so try changing data to this:
data: function() {
return {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
}
Maybe it will help.

Categories