How to insert in loop again inside loop then Insert query - php

$product_id = $request->input("product_id");
$size_id = $request->input("size");
$price = $request->input("price");
$shade_id = $request->input("shade_id");
$arr = array();
if($shade_id){
for($i=0; $i<count($shade_id); $i++){
$shades_id = $shade_id[$i];
if($size_id){
for($j=0; $j<count($size_id); $j++){
/*$insert = DB::table('tbl_product_shade_attributes')
->insertGetId(['product_shade_id' => $shade_id[$i], 'product_id'=> $product_id,'size_id' => 1, 'price'=> 200]);*/
$arr[$j] = [
'product_shade_id' => $shades_id,
'product_id'=> $product_id,
'size_id' => $size_id[$j],
'price'=> $price[$j]
];
}
}
}
}
I'm not pretty sure why it doesn't insert properly data on the database.
My HTML Structure:
MY Database Structure
My output is displaying on the console log
This is my FormData
Please see my AJAX FormData

Related

How to repeat fuction in php?

Is it possible to repeat a function when it has finished. For Example: I have a function for export mysql to json file with a limit of 100 data. if it is successful create a json file with 100 data. Then it will repeat the same function to create json file 100 more data (no duplicate data) until the data runs out.
my code for generate json file :
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson){
echo "Create Json File Success In :".$file;
}else{
echo "Create Json Failed";
}
}
the code can only generate a json file once, how can it be repeated after generating a successful json file
note: I added a flag for each successful data generated json file
You can extract your codes to a function and use the function in the loop.
Example:
function exporter($limit = 100)
{
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT($limit)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson) {
echo "Create Json File Success In :".$file;
} else {
echo "Create Json Failed";
}
}
$numberOfRows = 10000; # use the count query here
$limit = 100;
while($numberOfRows > 0) {
exporter($limit);
$numberOfRows -= $limit;
}
Also, you can call your function in your function recursively (https://www.w3schools.blog/php-recursive-functions)
Putting the existing code in a loop seems like the obvious answer here.
do {
$results = $db
->SELECT()
->FROM(
['MM'=>'M_MEMBER'],
[
'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS',
]
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()
->FETCHALL();
if (count($results) === 0) {
break;
}
$data = [];
foreach ($results as $row) {
$row['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$data[] = $row;
//
// this is UNSAFE and inefficient, use a prepared statement if possible
//
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$json = json_encode($out);
$filename = sprintf(
"%sdataMember_%s_%s.json",
$store_path_pos,
date("Y-m-d"),
formatNbr($counterFile)
);
if ($json && file_put_contents($filename, $json)) {
echo "Create Json File Success In $file";
} else {
echo "Create Json Failed";
}
} while (true);
I fixed a few inefficiencies in your code; I have no idea what DB library you're using but as a rule you should never inject variables into an SQL query. It's likely safe in this context, but if your library allows you should prepare the statement outside the loop and execute it inside the loop for better performance.

How to loop through appended inputs inside an array

I'm submitting appended inputs through an API. The number of items is different every time. When I submit the form, the input is submitted successfully and an object is returned, but only the last appended input is submitted. How can I run a loop inside of the array shown, or what syntax of loop works here so that I will submit a new item for each appended input? thank you for considering.
<script>
$(document).ready(function(){
$("#new").click(function(){
$("table").append("<tr><td><input type= 'text' name = 'item[]'</td> </tr>");
});
});
</script>
<?php
after a form/table with input name="item[]" my PHP:
if (isset($_POST['submit']))
{
$size = sizeof($_POST['item']);
for ($i = 0; $i < $size; $i++)
{
$product = $_POST['item'][$i];
}
$fields = array(
'customer' => 992058,
'items' => [
[
'name' => $product,
]
]
);
// HERE IS A CURL CALL that POSTS $fields AND RETURNS JSON
?>
the JSON I'd like to see returned might look something like
"items":[{"name":"product1"}][{"name":"product2"}];
instead of what I'm getting which is
"items":[{"name":"product2"}]
Here is what you need to:
if (isset($_POST['submit']))
{
$size = sizeof($_POST['item']);
$products = [];
for ($i = 1; $i < $size; $i++)
{
$products[]['name'] = $_POST['item'][$i];
}
$fields = array(
'customer' => 992058,
'items' => $products
);
The problem with your code that var $product get only the last insert while running through the loop, you need to create an array inside the loop.

Update multiple records in codeigniter using active records

I'm trying to update multiple records in codeigniter using update_batch, but it doesn't work. here's my code
public function update {
$id = $this->input->post('id');
$id_sumber = $this->input->post('id_sumber');
$nominal = $this->input->post('nominal');
$jumlah = count($id);
$data = array();
for ($x=0; $x< $jumlah; $x++){
$data[] = array(
'id' => $id[$x],
'id_sumber' => $id_sumber[$x],
'nominal' => $nominal[$x]
);
}
$this->db->update_batch('road_map',$data,'id');
}
change this line:
$this->db->update_batch('road_map',$data,'id');
Id must be array of where condition.

Encode nested JSON array in php

I want to send nested JSON array.Which contain following format.
${"posts":[{
"abc":"123",
"xyz":"123",
"pro":[{
"name":"Brinjal",
"qty":"500 gms"
},
{
"name":"Brinjal",
"qty":"500 gms"
}]
}]
}
Here is my php code:
$rows = $stmt->fetchAll();
if ($rows) {
$order["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["order_id"] = $row["order_id"];
$post["order_totalamount"] = $row["order_totalamount"];
$post["address"] = $row["address"];
$post["pincode"] = $row["pincode"];
$post["delivery_timeslot"] = $row["delivery_timeslot"];
$post["order_date"] = $row["order_date"];
$query1= "query";
$rows1 = $stmt->fetchAll();
if ($rows1) {
foreach ($rows1 as $row1) {
$query2= "query";
$rows2 = $stmt->fetchAll();
$post["product"] = array();
if ($rows2) {
$products = array();
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
array_push($post["product"],$products);
echo json_encode($products);
}
}
}
array_push($order["posts"], $post);
}
echo json_encode($order);
}
From above code I got result:
$ {"posts":
[{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[{"product_name":"Brinjal","prod_qty":"500 gms"}]
}]
}
But my actual product array is:
${"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"}
Kindly help out. I am stuck on it. tried a lot but did not get success.
In
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
You overwrite $products["product_name"]and $products["prod_qty"] with the values of the last $row2.
The line {"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"} actually consists of two echo's:
{"product_name":"Banana","prod_qty":"1 Kg"}
{"product_name":"Brinjal","prod_qty":"500 gms"}
But you don't see the difference. I suggest echoing a string in-between them or use something like var_dump() to see how many values you're echoing.
You should do something like:
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]["product_name"]=$rows2[$i]["product_name"];
$products[$i]["prod_qty"] = $rows2[$i]["product_minquantity"];
}
This will result in: [{"product_name":"Banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
FYI $array[] = has the same rsults as array_push(), but had less overhead of calling array_push().
EDIT:
Below a complete example since it doesn't seem to workout for you:
//Demo $order
$order = array (
'posts' =>
array (
0 =>
array (
'order_id' => '18',
'order_totalamount' => '40',
'address' => '2, Chetan Society, Vadodara',
'pincode' => '390023',
'delivery_timeslot' => 'Zone wise delivery',
'order_date' => '2016-03-18 17:50:53',
),
),
);
//Demo $rows2
$rows2 = array(
array(
'product_name' => 'banana',
'product_minquantity' => '1 Kg'
),
array(
'product_name' => 'Brinjal',
'product_minquantity' => '500 gms'
)
);
$post['product'] = array();
if ($rows2) {
$products = array();
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]['product_name'] = $rows2[$i]['product_name'];
$products[$i]['prod_qty'] = $rows2[$i]['product_minquantity'];
}
$post['product'] = $products;
echo json_encode($products); //[{"product_name":"banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
}
//$order['posts'][] = $post;
$order['posts'][0] = $order['posts'][0] + $post;
//In this example I only have 1 item in $order['posts'] so I know to add to key 0.
//In your case you need to know which key of $rows1 you need to do the adding.
//Change the foreach loop of $rows to a for loop as well so you can define your own keynames ($i).
echo '<br>==================================================================<br>';
echo json_encode($order);
/*
{
"posts":[
{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[
{
"product_name":"banana",
"prod_qty":"1 Kg"
},
{
"product_name":"Brinjal",
"prod_qty":"500 gms"
}
]
}
]
}
*/

How to write a textfile with a condition using PHP

I have a problem in my code. My code is all about updating/deleting rows in textfile ig the textfile is found. I am having a trouble with it. At first I can add a new textfile and together with it I can also update this file. But it is for 1 row. If I update another row. It will just append the updated value at the end of the textfile. What I want is to update this or delete and insert the new one. But I don't know how. My process in updating the array is array_replace(). First I need to find out if the ID of my data is found in the textfile. If found I will simple update/delete and replace the existing data into my new updated data. If not found just add only.
Here's my code for that.
$restaurant_id = $post_data['company_id'];
$new_lat_entry = $post_data['new_lat'];
$new_long_entry = $post_data['new_long'];
/****Here's my new updated array ****/
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
/****This is the BASE array from the existing textfile ****/
$data = unserialize(file_get_contents('addresses.txt'));
$target = $data_add['restaurant_id'];
for ($i = 0; $i < count($data); $i++) {
$get_id = $data[$i]['restaurant_id'];
if($get_id == $target){
//If ID is found - UPDATE
$add_data = array();
$add_data = array(
$i => $data_add
);
$new_array = array();
$new_array = array_replace($data,$add_data);
$serialize_data = serialize($new_array);
$file_input_txt = fopen("addresses.txt","w+");
fwrite($file_input_txt,$serialize_data);
fclose($file_input_txt);
}else{
$new_array = array(
$i => $data_add
);
$serialize_data = serialize($new_array);
$file_input_txt = fopen("addresses.txt","w+");
fwrite($file_input_txt,$serialize_data);
fclose($file_input_txt);
}
}
The output of my text file is in serialized form.
a:1:{i:0;a:4:{s:13:"restaurant_id";s:4:"1519";s:7:"new_lat";s:8:"14.63823";s:8:"new_long";s:9:"121.02999";s:12:"date_updated";s:19:"2013-11-15 12:42:59";}}
That's all guys please help me. I have a deadline now. And I am stuck with it. :-( This is the first time I am creating a CRUD based on a text file that's why I am having a trouble debugging it.
Can you please try this,
<?php
/****This is the BASE array from the existing textfile ****/
$data = unserialize(file_get_contents('addresses.txt'));
$restaurant_id = '1519';
$new_lat_entry = '14.64823';
$new_long_entry = '121.45999';
/****Here's my new updated array ****/
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
$target = $data_add['restaurant_id'];
$Count =count($data);
$new_array =array();
for ($i = 0; $i < $Count; $i++) {
$get_id = $data[$i]['restaurant_id'];
//If ID is found - UPDATE
$add_data = array(
$i => $data_add
);
if($get_id == $target){
$new_array = array_replace($data,$add_data);
}
}
$serialize_data= serialize($new_array);
print_r($serialize_data);
$file_input_txt = fopen("addresses.txt","w+");
fwrite($file_input_txt, $serialize_data);
fclose($file_input_txt);
?>

Categories