I have an issue with one of API, where this API will create Order information. Each Order represents 1 buyer with multiple items. I want to loop the items in my API method. But, when I try to loop the function, it only stores the first array value, which is not what I want. I want to store a whole array of values to the Database.
Here is the API Code:
$s = $data->ItemIDs;
if($order->CreateOrderInfo()){
echo 'Order created successfully.';
echo "---";
for($i = 0; $i < sizeof($s); $i++){
$order->ItemCode = $s[$i];
$order->GetItemInfo();
if ($order->ItemCode != null){
$item_array = array(
'UserMememberNo' => $order->UserMememberNo,
'Image' => $order->Image,
'Description' => $order->Description,
'Price' => $order->Price,
'ItemBrand' => $order->ItemBrand,
'ItemModel' => $order->ItemModel
);
//GET DATA FOR ITEM TABLE
$order->ItemGUID = $data->ItemGUID;
$order->ItemName = $order->Description;
$order->ItemPrice = $order->Price;
$order->ItemQuantity = $data->ItemQuantity;
$order->ItemVariation1 = $data->ItemVariation1;
$order->ItemVariation2 = $data->ItemVariation2;
$order->ItemVariation3 = $data->ItemVariation3;
$order->ItemVariation4 = $data->ItemVariation4;
$order->ItemVariation5 = $data->ItemVariation5;
}
else{
echo json_encode('No item Found');
}
if($order->CreateItemInfo())
{
echo 'Item created';
}else{
echo 'Unable to create item';
echo '----';
}
}
if($order->CreateBuyerInfo()){
echo 'Buyer information created';
}else{
echo 'Unable to create buyer information';
}
Here is the model. This model is for inserting the values into the Database:
//CREATE FUNCTION FOR ITEM TABLE
public function CreateItemInfo() {
$sqlQuery = "INSERT INTO ".$this->item_info_table."
SET
GUID = :GUID,
ItemGUID = :ItemGUID,
ItemName = :ItemName,
ItemPrice = :ItemPrice,
ItemQuantity = :ItemQuantity,
ItemVariation1 = :ItemVariation1,
ItemVariation2 = :ItemVariation2,
ItemVariation3 = :ItemVariation3,
ItemVariation4 = :ItemVariation4";
$stmt = $this->conn->prepare($sqlQuery);
$this->GUID = htmlspecialchars(strip_tags($this->GUID));
$this->ItemGUID = htmlspecialchars(strip_tags($this->ItemGUID));
$this->ItemName = htmlspecialchars(strip_tags($this->ItemName));
$this->ItemPrice = htmlspecialchars(strip_tags($this->ItemPrice));
$this->ItemQuantity = htmlspecialchars(strip_tags($this->ItemQuantity));
$this->ItemVariation1 = htmlspecialchars(strip_tags($this->ItemVariation1));
$this->ItemVariation2 = htmlspecialchars(strip_tags($this->ItemVariation2));
$this->ItemVariation3 = htmlspecialchars(strip_tags($this->ItemVariation3));
$this->ItemVariation4 = htmlspecialchars(strip_tags($this->ItemVariation4));
$stmt->bindParam(":GUID", $this->GUID);
$stmt->bindParam(":ItemGUID", $this->ItemGUID);
$stmt->bindParam(":ItemName", $this->ItemName);
$stmt->bindParam(":ItemPrice", $this->ItemPrice);
$stmt->bindParam(":ItemQuantity", $this->ItemQuantity);
$stmt->bindParam(":ItemVariation1", $this->ItemVariation1);
$stmt->bindParam(":ItemVariation2", $this->ItemVariation2);
$stmt->bindParam(":ItemVariation3", $this->ItemVariation3);
$stmt->bindParam(":ItemVariation4", $this->ItemVariation4);
if($stmt->execute()) {
return true;
}
return false;
}
A screenshot below shows the issue, where only the first value of the array is successfully inserted to the Database.
Result of Database Insert
Related
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 want to create a condition which a user would choose whether he wants to use an input which means a database would create an auto_incremented id or he wants to use an older data which will not use new id but only use it. i have used dropdown database populate for my old input.
My Dropdown list
//get contractor list
$Contractor_List = $this->foo_pro->get_list_contractors();
$opt = array('' => '');
foreach ($Contractor_List as $Contractor_No) {
$opt[$Contractor_No] = $Contractor_No;
}
$data['con_list'] = form_dropdown('',$opt,'','ProjectID = "Contractor_No" name="contractorNo" id="" class="w3-select w3-border w3-hover-light-grey"');
My Controller
public function save_createdProject()
{
$data_project = array();
$data_contractor = array();
//project data
if ($this->input->post('year') === '') {
$data_project['P_Year'] = 15;
}else{
$data_project['P_Year'] = $this->input->post('year');
}
if ($this->input->post('code') === '') {
$data_project['Code'] = 'KO';
}else{
$data_project['Code'] = $this->input->post('code');
}
$data_project['ProjectID'] = $this->input->post('project');
$data_project['Contract_Amount'] = $this->input->post('camount');
//contractor data
if ($this->input->post('cname') === '' && $this->input->post('caddress') === '') {
$data_project['Contractor_No'] = $this->input->post('contractorNo');
}else{
$data_contractor['Contractor_Name'] = $this->input->post('cname');
$data_contractor['Contractor_Address'] = $this->input->post('caddress');
}
$this->foo_pro->add_project($data_project, $data_contractor);
redirect('Main/project','refresh');
//var_dump($data);exit;
}
My Model
public function add_project($data_project, $data_contractor)
{
//contractor
$this->db->insert('contractor', $data_contractor);
$Contractor_No = $this->db->insert_id();
//project
$data_project['Contractor_No'] = $Contractor_No;
$this->db->insert('project', $data_project);
$ProjectID = $this->db->insert_id();
}
this here is my problem except inserting the older data which is the contractor_no 1 it creates another data that would insert as contractor_no 4.. but also i need to insert new data for new contractor_name..
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.
i used an exsiting code from a tutorial and need to change it.
The original code doesnt use an array, but i need it.
In my index.php i am calling the function with a tag:
else if ($tag == 'getinvbykost') {
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
the function GetInvByKost($kstalt); is defined in DB_Functions.php.
the part is:
public function GetInvByKost($kstalt) {
$result = mysql_query("SELECT ean, name, betriebsdatenalt FROM geraete WHERE kstalt='$kstalt' AND accepted='0'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while ($result = mysql_fetch_assoc($result)){
}
return $result;
//echo $result[1];
}
else {
// user not found;
return false;
}
}
the problem is, the function GetInvByKost returns an array.
the part in the index.php
$response["success"] = 1;
$response["ean"] = $get["ean"];
$response["name"] = $get["name"];
$response["betriebsdatenalt"] = $get["betriebsdatenalt"];
isnt made for an array, only for a single line.
how do i can get the values in the array to build my output?
mysql_fetch_assoc($result) returns a flat array. This means you can't access returned array by a key. So $get["ean"] is wrong and $get[1] is correct. You can access result of mysql_fetch_assoc($result) only by index, not key. You have SELECT ean, name, betriebsdatenalt... in your query, so index of "ean" is equal to 0, "name" is equal to 1 and so on. Therefore, 3 parts of your code should be change in this way:
`$get["ean"]` => ` $get[0]`
`$get["name"]` => `$get[1]`
`$get["betriebsdatenalt"]` => `$get[2]`
Update:
So, the index.php file should be like this:
else if ($tag == 'getinvbykost') {
$response = array();
$kstalt = $_POST['kstalt'];
$get = $db->GetInvByKost($kstalt);
if ($get != false) {
// echo json with success = 1
$response["success"] = 1;
$response["ean"] = $get[0];
$response["name"] = $get[1];
$response["betriebsdatenalt"] = $get[2];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "nicht erfolgreich";
echo json_encode($response);
}
}
I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.