I have searched everywhere, but nothing I find seems to help solve this. I have a html web form (in a PHP document) that writes data to a CSV file, and below the form is a table that filters the CSV data back in based on a key word. I have no problems with my existing code for that part. However, I need to have an auto-number function that assigns a number to each form. I need help on even where to start. I'm still relatively new to coding, so any help would be great. Edit: Here is the code I use to write my data to the csv file.
if($_POST['formSubmit'] == "Submit")
{
$fs = fopen("fixturerequests.csv","a");
fwrite($fs,$varFixNum . ", " . $varRequester . ", " . $varDept . ", " . $varSupervisor . ", " . $varDesc . ", " . $varParts . ", " . $varWC . ", " . $varAddinfo . ", " . $varDateReq . ", " . $varDateNeed . ", " .$varStatus . "\n");
fclose($fs);
header("Location: successfullysubmitted.php");
exit;
}
Any guidance would be excellent. Thank you.
You can use this function
function next_available_form_id(){
$rows = file('fixturerequests.csv'); //put our csv file into an array
if(empty($rows)) return 1; //if our csv is empty we start from 1
$data = str_getcsv(array_pop($rows)); //array_pop gets the last row
return $data[0]+1; //we get first field and add 1 to it
//Just use the field where you store the form number
//e.g if you store the form number in the
//4th field replace $data[0] with $data[3]
}
Based on the code you provided you can use the function I provided to get the next form_id before storing it in the csv file.Just make this modification to your code after opening the csv file :
$fs = fopen("fixturerequests.csv","a");
$form_id=next_available_form_id(); //ADD THIS to get the next available id
//And insert $form_id as the first field in your csv file
fwrite($form_id,$fs,$varFixNum . ", " . $varRequester . ", " . $varDept . ", " . $varSupervisor . ", " . $varDesc . ", " . $varParts . ", " . $varWC . ", " . $varAddinfo . ", " . $varDateReq . ", " . $varDateNeed . ", " .$varStatus . "\n");
Notice: Of course since the csv you have now does not have form_id as the first field you should either create your csv file from scratch or add form numbers in your existing records.In the example I use awk to do that:
awk '{printf "%d,%s\n", NR, $0}' < fixturerequests.csv