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'
];
Related
I want to make function that update client.client_status data from given $id parameters from controller end function that fetched from booking.booking_id
Here my controller
function end($book_id = null) {
if (!empty($book_id)) {
// Booking Table
$table = 'booking';
$where = [
'book_id' => $book_id,
];
$data = [
'room_status' => 1,
];
$this->Model_Data->booking_update($table, $where, $data);
// Client Table
$table = 'client';
$client_id = $???????; // How to get booking.client_id from given id parameters
$where = [
'client_id' => $client_id,
];
$data = [
'room_status' => 1,
];
$this->Model_Data->booking_update($table, $where, $data);
$this->session->set_flashdata('book_ended', 'Book Ended');
redirect('book');
}
else {
$this->session->set_flashdata('book_end_error', 'Book End Error');
redirect('book');
}
}
Here my SQL Tables
According to your comment in Question , book_by_client_id is equal to client_id then for :
Accessing a single row:
(1) Result as an Object
$data_result = $this->db->get_where('booking',array('book_id'=>$book_id ))->row();
$book_by_client_id =$data_result->book_by_client_id;
$client_id = $book_by_client_id; // client_id
(2) Result as an Array
$data_result = $this->db->get_where('booking',array('book_id'=>$book_id ))->row_array();
$book_by_client_id =$data_result['book_by_client_id'];
$client_id = $book_by_client_id; // client_id
Note : for more info about row(); && row_array();
https://codeigniter.com/userguide3/database/results.html#result-rows
I have a table that I have recently edited to add another index using two columns (which combined are required to be unique).
The problem is now I get an error when I go to create a new model record:
Integrity constraint violation: 1062 Duplicate entry ... for key ....
The two columns are titled:
shipment_origin
pro_number
So as an example, the end result would look like: 1-230185
And I have checked, the record is created technically, it just doesn't follow through and the error is returned. So to make it simple, there is no record before hand (so there's no duplicate entry), a record is created in the database and the error is returned (no matter what).
Or is there a way to go about doing this directly through Laravel rather than MySQL?
Update
Here is the public function in my controller:
public function store(Request $request)
{
$this->validate(request(), [
'pro_number' => 'required',
'shipment_origin' => 'required'
/*'piecesNumber' => 'required' (had to remove for now, but must review)*/
]);
$user_id = Auth::id();
$input = $request->all();
//Save Initial Shipment Data
$shipment = new Shipment();
$shipment->pro_number = request('pro_number');
$shipment->shipment_origin = request('shipment_origin');
$shipment->date = request('date');
$shipment->due_date = request('due_date');
$shipment->tractor_id = request('tractor_id');
$shipment->trailer_id = request('trailer_id');
$shipment->driver_id = request('driver_id');
$shipment->notes = request('notes');
$shipment->shipper_no = request('shipper_no');
$shipment->ship_to = request('ship_to');
$shipment->ship_from = request('ship_from');
$shipment->bill_to = request('bill_to');
$shipment->bill_type = request('bill_type');
$shipment->load_date = request('load_date');
$shipment->shipment_status = 1;
$shipment->shipment_billing_status = (isset($request->shipment_billing_status) && !empty($request->shipment_billing_status)) ? $request->shipment_billing_status : 1;
$shipment->created_by = $user_id;
$shipment->cn_billtoName = request('cn_billtoName');
$shipment->cn_billtoAddress1 = request('cn_billtoAddress1');
$shipment->cn_billtoAddress2 = request('cn_billtoAddress2');
$shipment->cn_billtoCity = request('cn_billtoCity');
$shipment->cn_billtoState = request('cn_billtoState');
$shipment->cn_billtoZip = request('cn_billtoZip');
$shipment->cn_billtoEmail = request('cn_billtoEmail');
$shipment->cn_billtoPhone = request('cn_billtoPhone');
$shipment->cn_shiptoName = request('cn_shiptoName');
$shipment->cn_shiptoAddress1 = request('cn_shiptoAddress1');
$shipment->cn_shiptoAddress2 = request('cn_shiptoAddress2');
$shipment->cn_shiptoCity = request('cn_shiptoCity');
$shipment->cn_shiptoState = request('cn_shiptoState');
$shipment->cn_shiptoZip = request('cn_shiptoZip');
$shipment->cn_shiptoEmail = request('cn_shiptoEmail');
$shipment->cn_shiptoPhone = request('cn_shiptoPhone');
$shipment->cn_shipfromName = request('cn_shipfromName');
$shipment->cn_shipfromAddress1 = request('cn_shipfromAddress1');
$shipment->cn_shipfromAddress2 = request('cn_shipfromAddress2');
$shipment->cn_shipfromCity = request('cn_shipfromCity');
$shipment->cn_shipfromState = request('cn_shipfromState');
$shipment->cn_shipfromZip = request('cn_shipfromZip');
$shipment->cn_shipfromEmail = request('cn_shipfromEmail');
$shipment->cn_shipfromPhone = request('cn_shipfromPhone');
$shipment->fuelChargeDesc = request('fuelChargeDesc');
$shipment->fuelChargeAmt = request('fuelChargeAmt');
$shipment->fuelChargeTotal = request('fuelChargeTotal');
$shipment->permitChargeDesc = request('permitChargeDesc');
$shipment->permitChargeAmt = request('permitChargeAmt');
$shipment->permitChargeTotal = request('permitChargeTotal');
$shipment->otherChargeDesc = request('otherChargeDesc');
$shipment->otherChargeAmt = request('otherChargeAmt');
$shipment->otherChargeTotal = request('otherChargeTotal');
$shipment->noCharge = request('noCharge');
$shipment->noSettle = request('noSettle');
$shipment->Total = request('Total');
if ((request('shipment_billing_status') == 2) || (request('shipment_billing_status') == 3)){
$balance = 0.00;
}else{
$balance = request('Total');
}
$shipment->Balance = $balance;
$shipment->freightBillSubtotal = request('freightBillSubtotal');
$shipment->save();
//Save Shipment Details
for ($i = 0; $i < count($request->shipment_details['piecesNumber']); $i++) {
//the first line used to be 'shipment_id' => $shipment->pro_number,
Shipment_Detail::create([
'shipmentID' => $shipment->id,
'pieces_number' => $request->shipment_details['piecesNumber'][$i],
'pieces_type' => $request->shipment_details['piecesType'][$i],
'rate_type' => $request->shipment_details['rateType'][$i],
'charge' => $request->shipment_details['charge'][$i],
'weight' => $request->shipment_details['weight'][$i],
'hazmat' => $request->shipment_details['hazmat'][$i],
'description' => $request->shipment_details['description'][$i] ]);
}
$carrier = \App\Customer::where('carrier','=',1)->get();
foreach($carrier as $car){
$carrierUsers = $car->users;
if ($carrierUsers->count() > 0){
foreach($carrierUsers as $carrierUser){
$carrierUser->notify(new FreightBillNew($shipment));
}
}
}
Session::flash('success_message','Freight Bill Successfully Created'); //<--FLASH MESSAGE
//Return to Register//
return redirect('/shipments/accounts');
}
i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.
This is my sample code:
switch($topic_type) {
case 1: //post
$model = 'Userposts';
$field_name = 'user_post_id';
$select_name = 'post_title';
break;
}
$model = ClassRegistry::init($model);
$model->alias = 'TP';
$model->id = $topic_id;
$result = $model->find('first',
array(
'conditions'=>array($field_name=>$topic_id),
'fields'=>array($select_name.' as topic',$field_name.' as id'),
));
if(!empty($result)){
$this->updata[$model_name][$select_name] = $modified_topic;
$this->updata[$model_name][$field_name] = $topic_id;
if($model->save($this->updata)){
$respArr['token'] = $token;
$respArr['status'] = 1;
$respArr['msg'] = 'Success';
echo json_encode(array('token' => $token, 'status' => 1, 'msg' => 'Success'));exit;
}
}
The $model->find is working and fetching result where as $model->save after find is not working.
field_name is the primary key and select_name is the save that i want to update after modifying title.
I have tried to add a php file as the source of data for a jquery calendar that uses json as below:
<script>
$(document).ready(function() {
$("#eventCalendarHumanDate").eventCalendar({
eventsjson: 'modules/events/json/event.humanDate.json.php',
jsonDateFormat: 'human'
});
});
</script>
The php file works when i echo variables only but when i connected to the database and looped, it fails and i get the error "error getting json" But running my code separately i get no error from the php file itself.
<?php
$hostname_app_conn = "localhost";
$database_app_conn = "xx";
$username_app_conn = "xx";
$password_app_conn = "";
$app_conn = mysql_pconnect($hostname_app_conn, $username_app_conn, $password_app_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_app_conn, $app_conn );
$query_rs_content = "SELECT * FROM `mod_events_events` WHERE `active`=1 ORDER BY `Id` LIMIT 365";
$rs_content = mysql_query($query_rs_content, $app_conn) or die(mysql_error());
$totalRows_rs_content = mysql_num_rows($rs_content);
header('Content-type: text/json');
echo '[';
$separator = "";
$days = 16;
$i = 1;
echo $separator;
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
echo ' { "date": "'.$row_rs_content['eventday'].'", "type": "'.$row_rs_content['type'].'", "title": "'.$row_rs_content['Title'].'", "description": "'.$row_rs_content['teasertext'].'", "url": "" },';
}
$separator = ",";
echo ']';
?>
thanks in advance.
You should use the json_encode() function, something like this:
//more code above
$array = new array();
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
$array[] = array(
'date' => $row_rs_content['eventday'],
'type' => $row_rs_content['type'],
'title' => $row_rs_content['Title'],
'description' => $row_rs_content['teasertext'],
'url' => '',
);
}
header('Content-type: application/json');
echo json_encode($array);
die();
Most likely you had some character not being escaped properly or something else that was causing it not to be a valid json array so Javascript is dying trying to parse it.