Jump to content

php and csv file


caps1277

Recommended Posts

hey guys,

im new to this forum and new to php and was hoping someone out there can help me out.

what i need to do is be able to delete or modify a specific line from the .csv file when the person clicks the delete or modify button next to the state and abbreviation (which is on state_form.php, the code is on state_manager.php).

i have some of the code, and as you can see, it deletes the first row of the .csv file no matter what delete button i push.

$filename = "states.csv"; // File which holds all data
$rowToDelete = 1; // This is line need to be deleted

$arrFp = file( $filename ); // Open the data file as an array
$numLines = count( $arrFp ); // Count the elements in the array

$fp = fopen( $filename, "w" ); // Open the file for writing

for($i=0; $i<$numLines; $i++) // Overwrite the content except the line to be deleted
{
    if($i != ($rowToDelete-1) )
    fwrite($fp, $arrFp[$i]);
}

fclose( $fp ); // Close the file

i have tried to modify this code to get it to come up with the specific line, but i can't seem to come up with something that works.  i hope you guys can help me out.  thanks
Link to comment
Share on other sites

caps,

nice to know I'm not the only new guy to phpfreaks. I don't work with files very often, usually just databases, so I'm a little rusty, but let me see if I can help out in any way.

1. Is it safe to assume that you are passing in the row number that you want to be deleted? It is hard-coded as 1 in your example here... but maybe you re-wrote that for posting.

2. Probably not the problem, but I think reading and writing from the same file can cause some fairly adverse behavior. (could be wrong here) Just for experimentation's sake, write out to another file and see what happens.
Link to comment
Share on other sites

http://www.the-silvas.com/cmis310.html

that is a hardcoded html file of what the php page looks like.

this is the code for the state_form.php

<form action="state_manager.php" method="POST">
NEW RECORD
<table>
<tr>
<td>
Abbr: <input type="text" name="abbr">
</td><td>
State: <input type="text" name="state_name">
</td>
<td>
<input type="submit" name="insert_state" value="Insert">

</td>
</tr>
</table>
</form>


<?php
$row = 1;
$handle = fopen("states.csv", "r");

?>
<form action="state_manager.php" method="GET">
MODIFY RECORDS
<table>
<?
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
?>
<tr>
<td>
Abbr: <input type="text" name="abbr" value="<?=$data[1]?>" readonly="readonly">
</td><td>
State: <input type="text" name="state_name" value="<?=$data[0]?>">
</td>

<td>
<input type="submit" onClick="return delete()" name="delete_state" value="Delete">
<input type="submit" name="modify_state" value="Save">
</td>
</tr>
<?
}
?>

when the user clicks the delete button, it should delete that row of the file.

the teacher gave me this information, but i don't know how to do it.

[quote]once the user clicks the DELETE button, your state_manager.php

should look at the Abbreviation $_POST[$abbr] (or whatever that field is called)...

Find that element on your associative array that holds all the elements of the state.csv file....

When you find it, delete that element from the array (research ways to delete items from an array)

Then, write the contents of the array back into the state.csv file

redirect user back to the state_form.php[/quote]

im guessing that this way can be used for modifying the state also?  (that is when the user clicks the save button.)
Link to comment
Share on other sites

This will work provided the file looks like

RI,Rhode Island
MA,Massachussetts

[code]<?
$search = $_POST['abbr'];
$filename = "states.csv";
$data=array();
$contents = file($filename);
foreach($contents as $val){
  $state = explode(",",$val);
  $data[$state[0]] = $state[1];
  }
  if (!$handle = fopen($filename, 'w')) {
        echo "Cannot open file ($filename)";
        exit;
  }
foreach($data as $abb => $name){
  if($abb <> $search){
  $line = $abb.",".$name;
  fwrite($handle, $line);
  }
}
fclose($handle);
?>[/code]

Ray
Link to comment
Share on other sites

As the form is currently written, craygo's code will only work for inserting, not for deleting lines. In the section of the form for modifying, you need to make the name attributes into arrays. If you don't, the form will always return the last state listed.

Ken
Link to comment
Share on other sites

The script above reads the csv file. Make an array of the existing data. Loops through the array to find the one you want to delete then writes it back to the csv file. if you wanted to recreate the array without the dleted one just add it to the second loop.

[code]<?php
$newdata = array();
foreach($data as $abb => $name){
  if($abb <> $search){
$newdata[$abb] = $name;
  $line = $abb.",".$name;
  fwrite($handle, $line);
  }
}
?>[/code]

now you have an array called $newdata with all your states minus the one you wanted to delete.

Ray
Link to comment
Share on other sites

hey man,

first off i want to say thanks for helping me out with this problem, it's really appreciated.

i can't seem to get the code to work.  i know you said in a previous post that the it would work if the file was written "KY, Kentucky", i checked and the file is written "Kentucky, KY".  i tried flopping some of the code around to accomidate this, but it still doesn't work for some reason.  any suggestions?
Link to comment
Share on other sites

[code]<?php
<?
$search = $_POST['abbr'];
$filename = "states.csv";
$data=array();
$contents = file($filename);
foreach($contents as $val){
  $state = trim(explode(",",$val));
  $data[$state[0]] = $state[1];
  }
  if (!$handle = fopen($filename, 'w')) {
        echo "Cannot open file ($filename)";
        exit;
  }
foreach($data as $name => $abb){
  if($abb <> $search){
  $newdata[$name] = $abb;
  $line = $name.",".$abb;
  fwrite($handle, $line);
  }
}
fclose($handle);
?>[/code]

Ray
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.