I want to calculate hargaLama and hargaBaru, then insert it into database. To do so, I retrieve hargaLama from a view in mysql to my controller while hargaBaru is a user input. Even though I'm using foreach I got Undefined variable hargaLama and I also got error
Unknown column 'kodeProduksi' in 'field list'.
Here's my controller:
public function proses_tambahBarang(){
$kode = $_POST['kode'];
$kodeProduksi = $_POST['kodeProduksi'];
$nama = $_POST['nama'];
$tipe = $_POST['tipe'];
$ukuran = $_POST['ukuran'];
$merk = $_POST['merk'];
$satuan = $_POST['satuan'];
$jumlah = $_POST['jumlah'];
$harga = $_POST['hargaSatuan'];
// echo "proses_tambahBarang";
$data_insert = array(
'kodeBarang' => $kode,
'kodeProduksi' => $kodeProduksi,
'namaBarang' => $nama,
'tipeBarang' => $tipe,
'ukuran' => $ukuran,
'merk' => $merk,
'satuan' => $satuan,
'jumlah' => $jumlah,
'hargaSatuan' => $harga,
'keterangan' => 'n/a',
'idUser' => $this->session->userdata('username'),
'waktuMasuk' => 'n/a',
'waktuEdit' => 'n/a'
);
//$cek = $this->mhome->Barang("where kodeBarang = $data_insert[kodeBarang]");
// if($cek >= 1)
// {
$cek = $this->mhome->BarangHistory("where kodeProduksi = '$data_insert[kodeProduksi]'");
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']));
if($cek >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = '$data_insert[kodeProduksi]'");
foreach ($query as $row) {
$hargaLama = $row[0]['hargaSatuan'];
$jumlahLama = $row[0]['jumlah'];
}
$hargaBaru = $data_insert['hargaSatuan'];
$jumlahBaru = $data_insert['jumlah'];
$jumlahBaru = $jumlahBaru + $jumlahLama;
$data_insert['jumlah'] = $jumlahBaru;
$data_insert['waktuEdit'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Updated";
$this->mhome->UpdateData('baranghistory',$data_insert,array("kodeProduksi" => $data_insert['kodeProduksi']));
$this->mhome->UpdateData('barang',$data_insert,array("kodeBarang" => $data_insert['kodeBarang']));
}
// $this->mhome->hitungHargaSatuan("where kodeBarang = '$data_insert[kodeBarang]'");
$hitung = $this->mhome->hitungHargaSatuan($data_insert['kodeBarang']);
if($hitung){
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
if($cek == 0) {
$data_insert['waktuMasuk'] = date("Y-m-d h:i:sa");
$data_insert['keterangan'] = "Baru";
$res = $this->mhome->InsertData('barang',$data_insert);
$res2 = $this->mhome->InsertData('baranghistory',$data_insert);
}
if($res >= 1 && $res2 >=1)
{
$this->session->set_flashdata('pesan','Tambah Barang Sukses');
redirect('userhome/index');
}
else {
echo "Tambah barang gagal";
}
}
And here's my model:
public function TableSelect($table,$where="")
{
$stmt = $this->db->query('select * from '.$table.' '.$where);
return $stmt->result_array();
}
I am sure you need not to put 0 here
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];//remove [0] from here
$jumlahLama = $row['jumlah'];//remove [0] from here
}
like this.you need to use count on codition because this is returned array.and use result_array() for getting result in array format.
$cek = $this->mhome->BarangHistory("where kodeProduksi = $data_insert['kodeProduksi']")->result_array();
// $cek = $this->db->get_where('baranghistory',array('kodeProduksi' =>$data_insert['kodeProduksi']))->result_array();
if(count($cek) >= 1);
{
$query = $this->mhome->TableSelect('listBarang',"where kodeProduksi = $data_insert['kodeProduksi']");
foreach ($query as $row) {
$hargaLama = $row['hargaSatuan'];
$jumlahLama = $row['jumlah'];
}
Related
I'm running through some distinct user ID's (about 147 of them, retrieved from a table with many duplicates) with a foreach loop and then when retrieved, using them to retrieve more user details. I then place these details within an array in order to push them to my JavaScript.
For some reason the result that I get from the array is what seems to be an infinite loop that has quit somewhere in the process.
Here's an example:
This is the code that I am currently running:
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
else
{
continue;
}
echo json_encode($past_threshold_users);
}
//echo json_encode($results);
wp_die();
}
Try this code
I have move this echo json_encode($past_threshold_users); code after foreach loop.
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
/*else
{
continue;
} */
}
echo json_encode($past_threshold_users);
//echo json_encode($results);
wp_die();
}
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.
We are trying to fetch value from database & display related value for all rows.
but code is fetching only first row value in DB & displaying same value for all rows.
Database
Site
function getDesignerCollection()
{
$i = 0;
foreach($order as $orderData)
{
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
$k = 0;
while ($k < count($orderitemsarray))
{
if($data['dpaid_status']=='P'){$dpaid_status='Paid';}
if($data['dpaid_status']=='U'){$dpaid_status='Unpaid';}
if($data['dpaid_status']=='R'){$dpaid_status='Returned';}
if($data['dpaid_status']==''){$dpaid_status='';}
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(
":dorder_id" => $orderData['entity_id']
));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
if ($roworders['dproduct_id'] == '')
{
$dorderStatus = "Unpaid";
}
else
{
$dorderStatus = $roworders['dpaid_status'];
}
$responce[] = array(
$orderData->getIncrementId() ,
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$dorderStatus
);
}
$k++;
$i++;
}
}
echo json_encode($responce);
}
full code : http://pastebin.com/GnT980nL
You need use fetchAll() instead fetch()
http://php.net/manual/ru/pdostatement.fetchall.php
Your function must looks like:
function getDesignerCollection() {
global $is_admin;
$user_home = new USER();
require_once '../../app/Mage.php';
Mage::app();
$stmts = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmts->execute(array(
":uid" => $_SESSION['userSession']
));
$rows = $stmts->fetchAll(PDO::FETCH_ASSOC);
}
Now in $rows you have array of associative arrays.
I'm really having a hard time to save this loop of mine in my system i need to ask if how many style they need for example they chose 3.. there's 3 table will appear and each table you need to write in quantity..
In my saving here's my codes
$numgen = $_POST['numgen']; //number of style (i chose 3 style)
$x= 1;
while($x <= $numgen)
{
$elements = array();
foreach ($_POST['barcode'.$x] as $barcode)
{
$stmt = $db->prepare("SELECT * FROM productmaterialnumber where materialnumber = :bid");
$stmt->execute(array(':bid' => $barcode)) or die(print_r($db->errorInfo(), true));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$productmaterialnumberID = $row['productmaterialnumberID'];
$matnum = $row['materialnumber'.$x];
$color = $row['color'];
$size = $row['size'];
$productgenericnumberID = $row['productgenericnumberID'];
$productstylecodeID = $row['productstylecodeID'];
$qty = $_POST[$matnum];
$totalqty += $qty;
$matnummm[] = $matnum."<br>";
$quantttt[] = $qty."<br>";
$sizzeeee[] = $size."<br>";
$colooor[] = $color."<br>";
}
$stmt = $db->prepare("INSERT INTO barcoderequest(reqID, buyerID, qty, materialnumber, ID, printstatus, division,
purrequest, dateadded, vendorID, remarks)
VALUES(:field0, :field1, :field2, :field3, :field4, :field5, :field6, :field7, :field8, :field9, :field10)");
$stmt->execute(array(':field0' => $defaultreqnum, ':field1' => $userID,
':field2' => $qty, ':field3' => $matnum, ':field4' => $ID, ':field5' => "Pending", ':field6' => $gennum.$division,
':field7' =>"Pending", ':field8' =>$currentdatetime, ':field9' => $vendor, ':field10' => $remarks))
or die(print_r($db->errorInfo(), true));
}
$x++;
}
If you notice i inserted $x beside $POST['barcode'.$x] $matnum = $row['materialnumber'.$x] so i can know the id but its not working but when i remove the $x it saves 3 times since i choose 3 style.
Can someone help me? THanks
$_POST['barcode'.$x] => not a collection so you cant loop over it.
Try this:
<?php
$_POST['numgen'] = 3;//For testing only (Needs to be removed!)
$numgen = $_POST['numgen'];
$_POST["barcode1"] = "1234566789"; //For testing only (Needs to be removed!)
$_POST["barcode2"] = "987654321"; //For testing only (Needs to be removed!)
$_POST["barcode3"] = "147852369"; //For testing only (Needs to be removed!)
$x= 1;
while($x <= $numgen)
{
foreach ($_POST as $key => $value) { //Loop over post instead of individual barcodes
$x="";
$barcode="";
if (strstr($key, 'barcode')) {
$x = str_replace('barcode', '', $key); //Get barcode number
$barcode = $value; // Get barcode
}
if ( $barcode != "") {
echo "Barcode".$x." :".$barcode."<br/>";//For testing only (Needs to be removed!)
$stmt = $db->prepare("SELECT * FROM productmaterialnumber where materialnumber = :bid");
$stmt->execute(array(':bid' => $barcode)) or die(print_r($db->errorInfo(), true));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$productmaterialnumberID = $row['productmaterialnumberID'];
$matnum = $row['materialnumber'.$x];
$color = $row['color'];
$size = $row['size'];
$productgenericnumberID = $row['productgenericnumberID'];
$productstylecodeID = $row['productstylecodeID'];
$qty = $_POST[$matnum];
$totalqty += $qty;
$matnummm[] = $matnum."<br>";
$quantttt[] = $qty."<br>";
$sizzeeee[] = $size."<br>";
$colooor[] = $color."<br>";
}
$stmt = $db->prepare("INSERT INTO barcoderequest(reqID, buyerID, qty, materialnumber, ID, printstatus, division,
purrequest, dateadded, vendorID, remarks)
VALUES(:field0, :field1, :field2, :field3, :field4, :field5, :field6, :field7, :field8, :field9, :field10)");
$stmt->execute(array(':field0' => $defaultreqnum, ':field1' => $userID,
':field2' => $qty, ':field3' => $matnum, ':field4' => $ID, ':field5' => "Pending", ':field6' => $gennum.$division,
':field7' =>"Pending", ':field8' =>$currentdatetime, ':field9' => $vendor, ':field10' => $remarks))
or die(print_r($db->errorInfo(), true));
$x++;
}
}
}
?>
I have little problem, I have no idea what's wrong with my code :/
$ilosc = $_POST["ilosc"];
$recipe = new Recipe();
$em = $this->getDoctrine()->getManager();
$repository = $this->getDoctrine()->getRepository('MainBundle:Recipe');
$query = $repository->createQueryBuilder('p')->select('p.id')->where('p.nazwa = :nazwa AND p.adres = :adres')->setParameters(array('nazwa' => $_POST["nazwaprzepisu"], 'adres' => $_POST["adresprzepisu"]))->getQuery();
$test = $query->getResult();
$id = $test[0]['id'];
$idprod = $_POST['idprod'];
$iloscprod = $_POST['iloscprod'];
for ($i = 0; $i < $ilosc; $i++)
{
$ingredient = new Ingredient();
$repositorying = $this->getDoctrine()->getRepository('MainBundle:Ingredient');
$query = $repositorying->createQueryBuilder('p')->select('p')->where('p.przepis_id = :id AND p.produkt_id = :idprod')->setParameters(array('id' => $id, 'idprod' => $idprod[$i]))->getQuery();
$result = $query->getResult();
if(!$result)
{
$ingredient->setProduktId($idprod[$i]);
$ingredient->setPrzepisId($id);
$ingredient->setIlosc($iloscprod[$i]);
}
else
{
$nowailosc = $result[0]['ilosc'] + $iloscprod[$i];
$stareid = $result[0]['id'];
echo "kokoko";
}
$em->persist($ingredient);
$em->flush();
}
I have problem with those two lines:
$nowailosc = $result[0]['ilosc'] + $iloscprod[$i];
$stareid = $result[0]['id'];
I get an error:
"Fatal error: Cannot use object of type My\MainBundle\Entity\Ingredient as array in".
Somebody have idea what I am doing wrong?
Problem solved. I had to use:
$nowailosc = $result[0]->getIlosc() + $iloscprod[$i];
$stareid = $result[0]->getId();