Adding a new row in a textfile using PHP

 

 How to append a new row in a text file using PHP

 

 

 

codingzon-write-form2textfile using pHP

 Manipulating text files is a common task when we are storing data in text files.  

This tutorial shows how to add or append a new line to an existing text file. 

There is a text file name: states.txt. In this file, each row is delimited with a semicolon.

There is another form.html file, take data from users and submits to PHP file.

PHP file receives submitted data and writes at the bottom of the states.txt file.

 

 States.txt file looks as follows:



form.html

<html>
<head>
<title>Codingzon Tutorials</title>
</head>
<body>

<h3> Please fill following details</h3>

<form action="demo.php" method="POST">
 
    State Name:
    <input type="text" name="statename" /><br />
    <br />Capital City :    
    <input type="text" name="capitalcity" /><br />
    <br /> Population:
    <input type="text" name="population" /><br />
    <input type="submit" value="submit" name="submit" />
    <br />
    </body>
    </html> 
 
 

 

demo.php

 
 
<?php

$rows  = file('states.txt');  // reading a file
$last_row = array_pop($rows);  // returns last row from the $rows.
$data = explode(";",$last_row); // spliting lastrow into words and storing in $data array
$id= $data[0]."<br />";   // reading id from $data
 
 if(isset($_POST['submit']))
  {
   if( $_POST["statename"] =="" or $_POST["capitalcity"] == "" or $_POST["population"] ){
    echo "Please all the fields"; exit;
   }
$statename   =   $_POST["statename"] ;
$capitalcity   =   $_POST["capitalcity"]; 
$population =   $_POST["population"]; 

// adds all the values to $row array

$row[] = ($id+1);
$row[] = $statename ;
$row[] = $capitalcity;
$row[] = $population; 


$strrow = implode(';', $row );  // converts the $row into string using delimiter ';'.

$strrow = "\r\n".$strrow
 
// opens a textfile with append mode 
 $fp = fopen('states.txt', 'a') or die("Couldn't open $file for writing!");
 
 fwrite($fp,$strrow)or die("Couldn't write values to file!"); // writes a string into file.
     
    fclose($fp);
    
  	echo "Record added to text file..";
 
}
 
 ?> 

 Result:

form:


 

 

 

 

 

 

states.txt 


 

A row is inserted in the states.txt at the bottom, after submitting data using the above form.


This code can be used with CSV files too. Just replace the delimiter (;) with (,) in implode and explode functions.

 

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Shoppingcart using PHP Sessions - Miniproject

Creating a new PDF by Merging PDF documents using TCPDF