How to save for loop inside while loop variable in PHP - php

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++;
}
}
}
?>

Related

Multiple table to encode json and display

Can someone help me to return JSON data with join tables? I have two tables which are sales_details and sales_payment. I want to return the data like this:
{
"sales_id":"3",
"sales_date":"2021-01-11 23:41:58",
"sales_po":"100549",
"sales_so":"1234",
"sales_dr":"5768",
"sales_si":"1794",
"sales_company":"",
"sales_cp":"",
"sales_particulars":"Authorized Personnel Only",
"sales_media":"Sticker on Sintra",
"sales_width":"16.00",
"sales_net_amount":"8601.60",
"sales_balance":"6601.60",
},
{
"payment_amount":"1000.00",
"payment_date":"2021-01-15",
"payment_remarks":""
},
{
"payment_amount":"1000.00",
"payment_date":"2021-01-18",
"payment_remarks":""
}
This what I've tried:
public function get_payment_info_by_id($payment_info_id) {
$query = $this->db->query(
"SELECT *
FROM tbl_sales_details AS tsd
INNER JOIN tbl_sales_payments AS tsp ON tsp.sales_id = tsd.sales_id
WHERE tsd.sales_id = $payment_info_id");
$jsonArray = array();
foreach($query as $row) {
$jsonArrayItem = array();
$jsonArrayItem['payment_amount'] = $row['payment_amount'];
$jsonArrayItem['payment_date'] = $row['payment_date'];
$jsonArrayItem['payment_remarks'] = $row['payment_remarks'];
array_push($jsonArray, $jsonArrayItem);
}
header('Content-type: application/json');
echo json_encode($jsonArray);
}
You can use the joined query but you must look at the result you get back and work out which parts are what you need in what part of the output
I am assuming you are using PDO and have converted the query to use perpared bound parameters.
Update Ahh I see you are using MYSQLI_ and not PDO, so I have changed the database access code. That will probably fix the undefined index errors
public function get_payment_info_by_id($payment_info_id) {
$sql = "SELECT *
FROM tbl_sales_details AS tsd
INNER JOIN tbl_sales_payments AS tsp ON tsp.sales_id = tsd.sales_id
WHERE tsd.sales_id = ?";
$stmt = $this->db->prepare($sql);
$stmt->bind_param('i', $payment_info_id);
$stmt->execute();
$result = $stmt->get_result();
$last_salesid = NULL;
$t = [];
while($row = $result->fetch_assoc()) {
if ( $last_salesid != $row['sales_id'] ) {
// get sales_details columns in this case
$t[] = [
"sales_id" => $row['sales_id'],
"sales_date" => $row['sales_date'],
"sales_po" => $row['sales_po'],
"sales_so" => $row['sales_so'],
"sales_dr" => $row['sales_dr'],
"sales_si" => $row['sales_si'],
"sales_company" => $row['sales_company'],
"sales_cp" => $row['sales_cp'],
"sales_particulars" => $row['sales_particulars'],
"sales_media" => $row['sales_media'],
"sales_width" => $row['sales_width'],
"sales_net_amount" => $row['sales_net_amount'],
"sales_balance": => $row['sales_balance']
];
$last_salesid = $row['sales_id'];
}
// then get the sales_payment info
$t[] = [
'payment_amount' => $row['payment_amount',
'payment_date'] => $row['payment_date',
'payment_remarks'] => $row['payment_remarks'
];
}
header('Content-type: application/json');
echo json_encode($t);
}

I'm getting what seems to be an infinite loop and can't figure out why - PHP/WordPress

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();
}

Auto increment Invoice ID in Code-igniter

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.

Codeigniter foreach Undefined variable

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'];
}

Array showing only first result good

I try to write this code on few ways, but always the result is good only for first team all other results are bad.
When I put id of some other club instead of $id I get the good result for that team but than is only one row, I want to show all 20 teams.
<table>
<thead><tr><th>Name</th><th>Played</th><th>0,5</th><th>1,5</th><th>2,5</th>
<th>3,5</th><th>4,5</th></tr></thead>
<tbody>
<?php
$teams = mysql_query("select * from teams");
$num_teams = mysql_num_rows($teams);
while ($group = mysql_fetch_row($teams)) {
$id_team[] = $group;
}
for ($a = 0; $a < $num_teams; $a++) {
if (isset($num_array)) {
mysql_data_seek($query_array, 0 );
$search_array_over = array();
}
$id = $id_team[$a][0];
$name_over = $id_team[$a][1];
$query_array = mysql_query("select * from full_stat where kl1 = $id or kl2 = $id");
$num_array = mysql_num_rows($query_array);
while ($row = mysql_fetch_row($query_array)) {
$data_over[] = $row;
}
$search_array_over = array('1' => '0', '2' => '0' ,'3' => '0', '4' => '0','5' => '0','6' => '0');
for ($now = 0;$now < $num_array; $now++) {
$over_pass = ($data_over[$now][3] + $data_over[$now][4]);
for ($pass = 1; $pass < 7; $pass++) {
if ($over_pass >= $pass) {
$final_pass = $pass;
}
else {
$final_pass = '6';
}
if (array_key_exists($final_pass, $search_array_over)) {
$search_array_over[$final_pass] += 1;
}
else {
$search_array_over[$final_pass] = 1;
}
}
}
echo '<tr><td>'.$name_over.'</td><td>'.$num_array.'</td> <td>'.$search_array_over[1].'</td><td>'.$search_array_over[2].'</td><td>'.$search_array_over[3].'</td><td>'.$search_array_over[4].'</td><td>'.$search_array_over[5].'</td></tr>';
}
?>
</tbody>
</table>
That is one confusing block of PHP code.
A better explanation of your final output would probably help here, but I'm going to guess it's the teamlist plus their statistics.
Since dissecting your current code strikes me as painful, I'm going to describe how I would do this instead.
In your database you have 2 tables, "team" and "team_stats"
Team Structure:
id int
name varchar
....
Stats Structure:
team_id int
someStat int
otherStat int
....
$stmt = $mysqli -> prepare("SELECT * FROM team LEFT JOIN team_stats ON team_stats.team_id");
$stmt -> execute();
$result = $stmt -> fetch_all();
foreach($result as $team) {
// output data to page
}
?>

Categories