FYI: I registered, waiting a bit for the confirmation email, requested a new confirmation, still haven’t received anything (nothing in junk mail folder either). Thankfully, you allow posts w/o registration makes it easy for cases like this.
I’m a php rookie, just learning the basics. I’m working on a simple file to help me better understand some of the principles behind the coding.
What I’m trying to do here, is have an html form where the user enters their first and last name, followed by the name of their pet. When they submit, it writes to a .txt file and prints out the names entered. This works just fine.
However, it also works when there is a blank entry (that is, when the variable has no data). I’ve used the if(empty()) function and tried to “break;” it if it is. But it doesn’t seem to work for me.
What I’d like it to do is not write to the .txt file if there is an empty field. The html is a simple form:
[code]
First Name:
Last Name:
Pet's Name:
And here is the php code (write_names.php)I have thus far (commented like crazy to help me remember what I’m doing.
[php]<?php
$filename = 'data/' . 'names.txt';
$fp = fopen($filename, 'a'); // opens file for appending
$cntr = 1;
while(true)
{
$name_html = 'name' . $cntr;
$name = $_POST[$name_html];
if (empty($name))
{
break;
}
$cntr++;
// Printing to screen
// print "Name: " . $name . "<br />";
$output_line = $name . " ";
fwrite($fp, $output_line);
}
fwrite($fp, "\n");
// debug
// print "name: '" . $name . "'";
fclose($fp);
//*****************
// Reading File
//*****************
// looks at FILE $filename, COUNTs the # of line [breaks], and stores that # in var $lines_in_file
// useful for when wanting to use FOR loop, and process 1 line in file at a time
$lines_in_file = count(file($filename));
// FOPEN will file open the file in the $var; "r" is for "reading" the file, then stores into $fp (file pointer)
$fp = fopen($filename, 'r'); //opens the file for reading
for ($ii = 1; $ii <= $lines_in_file; $ii++)
{
$line = fgets($fp); //Reads one line from the file
$names = trim($line); // gets rid of any whitespace to left or right of the line
print $names.'<br />';
}
//closes file completely
fclose($fp);
?>[/php]
Thanks in advance for any help provided.