How to write a textfile with a condition using PHP - 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);
?>

Related

How to insert in loop again inside loop then Insert query

$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

CakePHP 3 fast insertion/updating of records

I am trying to insert/update +/- 10k rows with a foreach loop. The complete loop duration is about 3-5minutes. Are there any tips on my code to do the insertion of update faster? The $rows are retrieved from a xls file converted to domdocument.
foreach($rows as $key => $row)
{
if($key < 1){continue;}
$cells = $row -> getElementsByTagName('td');
foreach ($cells as $cell) {
$project_id = $cells[0]->nodeValue;
$title = $cells[1]->nodeValue;
$status = $cells[2]->nodeValue;
$projectmanager = $cells[3]->nodeValue;
$engineer = $cells[4]->nodeValue;
$coordinator = $cells[5]->nodeValue;
$contractor_a = $cells[6]->nodeValue;
$contractor_b = $cells[7]->nodeValue;
$gsu = $cells[9]->nodeValue;
$geu = $cells[10]->nodeValue;
$query = $this->Projects->find('all')->select(['project_id'])->where(['project_id' => $project_id]);
if ($query->isEmpty()) {
$project = $this->Projects->newEntity();
$project->title = $title;
$project->project_id = $project_id;
$project->status = $status;
$project->projectmanager = $projectmanager;
$project->engineer = $engineer;
$project->coordinator = $coordinator;
$project->contractor_a = $contractor_b;
$project->contractor_b = $contractor_a;
$project->gsu = date("Y-m-d H:i:s");
$project->geu = date("Y-m-d H:i:s");
$project->gsm = date("Y-m-d H:i:s");
$project->gem = date("Y-m-d H:i:s");
if ($this->Projects->save($project)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}else{
debug($project->errors());
}
}else{
continue;
$query->title = $title;
$query->status = $status;
$query->projectmanager = $projectmanager;
$query->engineer = $engineer;
$query->coordinator = $coordinator;
$query->contractor_a = $contractor_b;
$query->contractor_b = $contractor_a;
$query->gsu = $gsu;
$query->geu = $geu;
if ($this->Projects->save($query)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}
}
}
//$this->Flash->error(__('The project could not be saved. Please, try again.'));
}
For faster bulk inserts don't use entities but rather generate insert queries directly.
https://book.cakephp.org/3.0/en/orm/query-builder.html#inserting-data
Ello, my vriend.
The TableClass->save() method is useful when saving one single record, in your case, you should use TableClass->saveMany() instead.
For this to happen, you need to treat your entities as arrays inside your foreach.
After the foreach, you will use another method from the tableclass (newEntities) to convert the array into entities before finally save them.
Basic example:
//Lets supose our array after our foreach become something like this:
$all_records =
[
//Each item will be an array, not entities yet
[
'name' => 'I.N.R.I.',
'year' => '1987',
'label' => 'Cogumelo',
'country' => 'Brazil',
'band' => 'Sarcófago',
'line_up' => '[{"name":"Wagner Antichrist","role":"Vomits, Insults"},{"name":"Gerald Incubus","role":"Damned Bass"},{"name":"Z\u00e9der Butcher","role":"Rotten Guitars"},{"name":"D.D. Crazy","role":"Drums Trasher"}]'
],
//Another record coming in..
[
'name' => 'Eternal Devastation',
'year' => '1986',
'label' => 'Steamhammer',
'country' => 'Germany',
'band' => 'Destruction',
'line_up' => '[{"name":"Marcel Schmier","role":"Vocals, Bass"},{"name":"Mike Sifringer","role":"Guitars"},{"name":"Tommy Sandmann","role":"Drums"}]'
]
];
//Time to get the tableclass...
$albums = TableRegistry::get('Albums');
//Time to transform our array into Album Entities
$entities = $albums->newEntities($all_records);
//Now, we have transformed our array into entities on $entities, this is the variable we need to save
if(!$albums->saveMany($entities))
{
echo "FellsBadMan";
}
else
{
echo "FellsGoodMan";
}
You can read more about here

How do i update multiple rows with multiple condition in Code Igniter

I am just learning PHP and using the Codeigniter framework.
I'm using this code in my controller when inserting new data and it's working.
//INSERT MULTI ROWS TABEL harga_inventori
$kode_inventori = $_POST['kode_inventori'];
$result = array();
foreach($_POST['kode_kategori_pelanggan'] AS $key => $val){
$result[] = array(
"kode_kategori_pelanggan" => $_POST['kode_kategori_pelanggan'][$key],
"kode_inventori"=>$kode_inventori,
"harga" => $_POST['harga_jual'][$key],
"diskon" => $_POST['diskon'][$key]
);
}
$res = $this->db->insert_batch('harga_inventori', $result);
redirect("inventori");
But when I'm using the same pattern for the updating function, it's not working at all.
for($i = 0; $i < count($_POST['harga_jual'][$i]); $i++) {
if($_POST['kode_kategori_pelanggan'][$i] != '') {
$res[] = array(
'harga' => $_POST['harga_jual'][$i],
'diskon' => $_POST['diskon'][$i],
);
$this->db->where('kode_inventori',$_POST['kode_inventori']);
$this->db->where('kode_kategori_pelanggan',$_POST['kode_kategori_pelanggan'][$i]);
$this->db->update('harga_inventori',$res);
}
}
redirect("inventori");
I'm trying the update_batch() but I got many errors, so I'm using for loop and updating a single row at a time.
What could be the problem here?
Its only a typo. You should pass the array $res not $data, and change $res[] to $res since it is not needed. You should also check with isset() to prevent errors of undefined:
for($i = 0; $i < count($_POST['harga_jual'][$i]); $i++) {
if(isset($_POST['kode_kategori_pelanggan'][$i])) {
$res = array(
'harga' => $_POST['harga_jual'][$i],
'diskon' => $_POST['diskon'][$i],
);
$this->db->where('kode_inventori',$_POST['kode_inventori']);
$this->db->where('kode_kategori_pelanggan',$_POST['kode_kategori_pelanggan'][$i]);
$this->db->update('harga_inventori',$res);
}
}
redirect("inventori");
It would help to see some of your data to know what you are trying to do. It seems a little strange that you initiate the counter $i at the same time using it as an array key in the for loop like this: for($i = 0; $i < count($_POST['harga_jual'][$i]); $i++)
It would help to know how the data in your $_POST looks like. You could try to remove the [$i] in your for loop. I would also check each POST variable it they are set before using them, something like:
for($i = 0; $i < count($_POST['harga_jual']); $i++) {
if(isset($_POST['kode_kategori_pelanggan'][$i])) {
// CHECK IF POST VARIABLES IS SET AND IF NOT SET A DEFAULT VALUE (IN THIS EXAMPLE AN EMPTY STRING):
$harga_jual = isset($_POST['harga_jual'][$i]) ? $_POST['harga_jual'][$i] : '';
$diskon = isset($_POST['diskon'][$i]) ? $_POST['diskon'][$i] : '';
$kode_inventori = isset($_POST['kode_inventori']) ? $_POST['kode_inventori'] : '';
$kode_kategori_pelanggan = $_POST['kode_kategori_pelanggan'][$i]; // ALREADY CHECKED ISSET ABOVE...
$data = array(
'harga' => $harga_jual,
'diskon' => $diskon,
);
$this->db->where('kode_inventori',$kode_inventori);
$this->db->where('kode_kategori_pelanggan', $kode_kategori_pelanggan);
$this->db->update('harga_inventori', $data);
}
}
redirect("inventori");

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.

How to update a specific line in a textfile using PHP?

Just need a little help here about my problem. I am trying to create a simple update in a textfile.
My goal is:
If the data is existed in the textfile. Don't add a new line in the file instead update that certain line.
If data is not existed simple add a new line in the file.
I have a problem in updating. I used the array_replace() function to do this but it always add a new line. My updates are always appending to the textfiles.
Here's my code I hope that you can help me.
//This is the new array from the user
$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 - It will get the text file if exsited
$data = unserialize(file_get_contents('addresses.txt'));
//get the ID of the new array - use for validation
$target = $data_add['restaurant_id'];
//loop the abase array
for ($i = 0; $i < count($data); $i++) {
//get the ID of the base array
$get_id = $data[$i]['restaurant_id'];
//compare base array ID and new array ID
if($get_id == $target){
// IF FOUND IN THE TEXTFILE
$add_data = array();
$add_data = array(
$i => $data_add
);
//replace the existed array in textfile with my updated array
$new_array = array();
$new_array = array_replace($data,$add_data);
//break;
}else{
//IF NOT FOUND, SIMPLY ADD
$new_array = array(
$i => $data_add
);
//fn_print_die($new_array);
}
}
//FOR DISPLAYING PURPOSES
echo "<pre>";
echo "BASE ARRAY<br />";
print_r($data);
echo "---------------------------------------------------------<br />";
echo "NEW ARRAY<br />";
print_r($add_data);
echo "---------------------------------------------------------<br />";
echo "REPLACED ARRAY<br />";
print_r($new_array);
echo "---------------------------------------------------------<br />";
//exit;
//SERIALIZE THE UPDATED ARRAY
$serialize_data = serialize($new_array);
//WRITE THE TEXTFILE
$file_input_txt = fopen("addresses.txt","a+");
fwrite($file_input_txt,$serialize_data);
fclose($file_input_txt);
//exit;
$array = unserialize(file_get_contents('addresses.txt'));
$file_input = fopen("addresses.csv","a+");
fputcsv($file_input, $data_add);
fclose($file_input);

Categories