I have a csv like this
product_id,stock_unit
1, ,
2, ,
3, ,
4, ,
5, ,
6, ,
Now in my php code I will get the product id and run a query to the database to get the stock unit from the database. After getting the stock unit for the product the script should update that to the csv without changing any names.
So for all that I have made my code like this
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$file = "update_pd.csv";
$csv = array_map("str_getcsv", file($file,FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);
$stock_array = array();
if (($handle = fopen($file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$stock_array[] = get_data($data[0]);
}
fclose($handle);
}
//print_r($stock_array);
$handle = fopen("update_pd.csv", "a");
fputcsv($handle, $stock_array);
function get_data($id) {
if( !empty($id) ) {
$result = $mysqli->query("SELECT `stock_unit` FROM `products` WHERE `product_id` = ".$id." ");
if( $result ) {
while($row = $result->fetch_assoc()) {
return $row['stock_unit'];
}
}
}
}
Here it is over writing the csv I mean the data is writing at the last line with all the older data present. The script should write the stock quantity according to the product id in the csv file without any changes in the csv header and file name. So can someone tell me how to do this? Any help and suggestions will be really appreciable.
Update
As the stock unit will be fetch from the database .The output should be like
product_id,stock_unit
1, 24,
2, 22,
3, 37,
4, 46,
5, 89,
6, 96,