SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Zealot
    Join Date
    May 2005
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Adding/Editing/Deleting From A Flat File

    Hi,

    I was wondering could anyone tell me the most efficient way to add, edit and delete data from a text file?

    I have a list of data, seperated by new lines. I'm displaying the data in an option tag eg.

    PHP Code:
    function getData() {
       
    $fp'includes/data.txt'
       
    $datafile($fp);
            
       
    // Sort Array Alphabetically
       
    sort($data);
            
       
    // Loop through array
       
    foreach ($data as $value) {    
          echo 
    "<option value=\"".$value."\">".$value."</option>\n";
       } 


    Then I make a form like:
    HTML Code:
    <form actions="actions.php" method="post">
       <select name="data">
          <?php getData(); ?>
       </select><br />
       <input type="submit" name="deldata" value="Delete Data" />
    </form>
    I want to take the $_POST['data'] from the form and search the file for a match and then if there is a match, delete the data from the file.

    Any help is greatly appreciated.

    If you require any further information, just ask.

    Cheers.

  2. #2
    SitePoint Addict
    Join Date
    Jun 2005
    Posts
    294
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The easiest way would be to create a MySQL database to hold the information as well. That way you can search the DB for entries... Then have your script pull out the DB information and write it to the .txt file.

    Steps:
    Add - Append to end of text file insert data... INsert into DB
    Edit - Edit Database first... OPen file and truncate using "w" then write to text file with information from db.. this will require a WHILE loop
    Delete - Same thing as above except delete from database first and then write to .txt file.

    I just don't know how to SEARCH a .txt file for an exact entry. And I don't know how to delete the line it's on. To met his seems the best way of doing.. Here is an example of the edit code.
    PHP Code:
    if(isset($_POST['submit'])){
    $sql mysql_query("UPDATE table SET field='$variable',field='$variable' WHERE id='$variable' LIMIT 1");
    $fp fopen("/usr/local/apache/name_of_file.txt""w");
    fclose($fp);
    $update mysql_query("SELECT * FROM users ORDER BY id");
    while (
    $r=mysql_fetch_array($update)){
      
    $user_1 $r['user'];
      
    $pass1_word $r['pass'];
      
    $fa fopen("/usr/local/apache/name_of_file.txt""a");
    fwrite($fa"$user_1:" $pass1_word "
    "
    );
    }
    fclose($fa);


  3. #3
    SitePoint Member
    Join Date
    Apr 2004
    Location
    Orange County
    Posts
    20
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Basically you just loop through the lines and if you find a line with a match unset it from the array.
    PHP Code:
    <?php
    $find 
    'some str';
    $lines file('youfile.ext');
    $rewrite false;
    foreach(
    $lines as $line_num => $line)
    {
        
    // replace strpos with preg_* or something for a more precise match
        
    if(strpos($line$find))
        {
            unset(
    $lines[$line_num]);
            
    $rewrite true;
        }
    }
    if(
    $rewrite)
    {
        
    $fp fopen('yourfile.ext''w');
        
    // you may not need this \n, I dont remember if it keeps the new lines when you file()
        
    fwrite($fpimplode("\n"$lines));
        
    fclose($fp);
    }
    ?>
    As Mav3n said this would be much easier to do with a database.

    If you dont have access to a db the other thing which can make dealing with flat-files much easier is to use serialize(). Basically you store your information as an array, then to store it you serialize the array and write the string to a file. Then to get your array structure back you read the file and unserialize the contents.

  4. #4
    SitePoint Enthusiast
    Join Date
    Nov 2004
    Location
    USA
    Posts
    26
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did this a similar way in the past writing a guestbook script. I would set each entry in the file with an id number, and use that id number to search the array if i was editing or deleting the line. Then rewrite the array back to the same file. It worked fine...took some time to figure out but it worked.

  5. #5
    SitePoint Zealot
    Join Date
    May 2005
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey, Thanks for the replies, i'll have a blast off that code Monday and let you know how I get on. Thanks again.

  6. #6
    SitePoint Evangelist
    Join Date
    Jun 2003
    Location
    Melbourne, Australia
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It would have helped if you'd said something about how the data is organised in the file. Assuming it's a series of entries, how is one entry differentiated from another? That is, of course, what your script would have to do.

    Mav3n and BigToach are right: databases are a good way to go, and they do the differentiation because each 'entry' is a separate record.
    Zealotry is contingent upon 100 posts and addiction 200?

  7. #7
    SitePoint Evangelist
    Join Date
    May 2004
    Location
    New Jersey, USA
    Posts
    567
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    spudz,

    The array_search function will locate elements of an array for you.

    PHP Code:
    $list = <<<NATIONS_OF_THE_WORLD
    United States, Canada, Mexico, Panama
    Haiti, Jamaica, Peru,
    Republic Dominican, Cuba, Carribean
    Greenland, El Salvador too.
    Puerto Rico, Columbia, Venezuela
    Honduras, Guyana, and still,
    Guatemala, Bolivia, then Argentina
    And Ecuador, Chile, Brazil.
    Costa Rica, Belize, Nicaragua, Bermuda
    Bahamas, Tobago, San Juan,
    Paraguay, Uruguay, Surinam
    And French Guiana, Barbados, and Guam.
     
    Norway, and Sweden, and Iceland, and Finland
    And Germany now one piece,
    Switzerland, Austria, Czechoslovakia
    Italy, Turkey, and Greece.
    Poland, Romania, Scotland, Albania
    Ireland, Russia, Oman,
    Bulgaria, Saudi Arabia
    Hungary, Cyprus, Iraq, and Iran.
    There's Syria, Lebanon, Israel, Jordan
    Both Yemens, Kuwait, and Bahrain,
    The Netherlands, Luxembourg, Belgium, and Portugal
    France, England, Denmark, and Spain.
     
    India, Pakistan, Burma, Afghanistan
    Thailand, Nepal, and Bhutan,
    Kampuchea, Malaysia, then Bangladesh (Asia)
    And China, Korea, Japan.
    Mongolia, Laos, and Tibet, Indonesia
    The Philippine Islands, Taiwan,
    Sri Lanka, New Guinea, Sumatra, New Zealand
    Then Borneo, and Vietnam.
    Tunisia, Morocco, Uganda, Angola
    Zimbabwe, Djibouti, Botswana,
    Mozambique, Zambia, Swaziland, Gambia
    Guinea, Algeria, Ghana.
     
    Burundi, Lesotho, and Malawi, Togo
    The Spanish Sahara is gone,
    Niger, Nigeria, Chad, and Liberia
    Egypt, Benin, and Gabon.
    Tanzania, Somalia, Kenya, and Mali
    Sierra Leone, and Algiers,
    Dahomey, Namibia, Senegal, Libya
    Cameroon, Congo, Zaire.
    Ethiopia, Guinea-Bissau, Madagascar
    Rwanda, Mahore, and Cayman,
    Hong Kong, Abu Dhabi, Qatar, Yugoslavia...
    Crete, Mauritania
    Then Transylviania,
    Monaco, Lichtenstein
    Malta, and Palestine,
    Fiji, Australia, Sudan.
    NATIONS_OF_THE_WORLD;
    // '

    $tempfile 'C:/temp/nations.txt';
    file_put_contents($tempfile$list)
        or die(
    "Failed to write file.");

    $items file($tempfile);
    sort($items);

    function 
    delete_item($item, &$array) {
        
    $index array_search($item$array);
        if (
    $index === FALSE) return;
        unset(
    $array[$index]);
    }

    function 
    edit_item($item$new_value, &$array) {
        
    $index array_search($item$array);
        
        if (
    $index === FALSE) {
            die(
    "Attempt to edit a non-existant item. Idiot.");
        }
        
        
    $array[$index] = $new_value;
        
    sort($array);
    }

    function 
    insert_item($new_item, &$array) {
        
    array_push($array$new_item);
        
    sort($array);
    }

    function 
    char_dump($str) {
        
    $ascii $hex "";
        
        for (
    $i 0$i strlen($str); ++$i) {
            
    $hex   .= sprintf("%02X "ord($str{$i}));
            
    $ascii .= " " . (ctype_print($str{$i}) ? $str{$i} : '?') . " ";
        }
        
        print 
    $ascii "\n" $hex "\n";
    }

    print 
    count($items) . "\n";
    delete_item("The Netherlands, Luxembourg, Belgium, and Portugal\r\n"$items);
    delete_item("France, England, Denmark, and Spain.\r\n"$items);

    print 
    count($items) . "\n";
    insert_item("Belrussia, Ukraine.\r\n"$items);

    print 
    count($items) . "\n";
    edit_item("The Spanish Sahara is gone,\r\n"
            
    "The Spanish Sahara is gone (aww!),\r\n"
            
    $items);

    print 
    count($items) . "\n"
    =Austin
    Austin Hastings - Principal Consultant - Longacre, Inc.

    Anything you can do, you can do better.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •