Search code examples
phparraysformsassociative-array

Add data to a csv and increase one of the values


Hello im gonna try to explain well this, its a little confusing

I have a .csv file, name users.csv with this format:

id name surname email

and with this data:

1 paul   harrison  [email protected]
2 robin  martinez  [email protected]
3 alma   halford   [email protected]

The thing is that i need to introduce the data from a form in to the csv, but the id element is not introduced when we get the data from the form, how can i do to increase id in one and add at the same time the data following the id in the same line?

<form style="text-align: center;" method="post">
    name: <input type="text" name="name">
    <br><br>
    surname: <input type="text" name="surname">
    <br><br>
    Email: <input type="email" name="mail">
    <br><br>
    Password: <input type="password" name="pwd">
    <br><br>
    smartphone: <input type="tel" name="smart">
    <br><br>
    city: <input type="text" name="city">
    <br><br>
    C.P: <input type="number" name="cp">
    <br><br>
    <input type="submit" name="send">
</form>

To add more information the idea is that the id column from the csv is increased each time is added data to the users.csv, each time we write data in the csv the id file is increased in one.


Solution

  • If you want to realize auto-increment behaviour like in SQL, just find a maximum ID and increase it on one. Result is your new identifier for new row.

    So to find maximum:

    $csv = ''; // here you csv
    $max = 0;
    foreach (explode("\n", $csv) as $row) {
      foreach (explode("\t", $row) as $index => $col) {
        if ($index == 0 && (int)$col > $max)
          $max = (int)$col;
      }
    }
    

    So as result you get maximum ID in $max variable. Just increase it on one and you have new identifier for new row as I say earlier.