Making a "Guestbook" need a form that saves input and outputs into a text file

So below is the code to the form…

I am working on a project for colllege, need to be able to store the input of a users: First, last name, and email.

Once it is stored, i need to append it to a text file, and output the stored names.

It is essentially a guestbook in the sense that everyone who submits the form, stores into the guestbook. And one of the links is to view the guest book.

Any help would be greatly appreciated, i am a novice php programmer. Thank you!!

[php]

Guest Form

Guest Book Form

Student First Name: 

Student Last Name: 

Email:  

[/php]

What do you need help with?

You can create a simple light weight database using SQLite3 though it wouldn’t create a text file, but a database file.

First you would need to create the database table.

I called this file createTable.php (I know how original ;D)
[php]<?php
class MyDB extends SQLite3
{
function __construct()
{
/* path to / database name */
$this->open(‘database/guest_book.db’);
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo “Opened database successfully\n”;
}

/* This creates the database table */
$sql =<<<EOF
CREATE TABLE guest_book
(id INTEGER PRIMARY KEY AUTOINCREMENT,
fname VARCHAR(25) NOT NULL,
lname VARCHAR(25) NOT NULL,
email text NOT NULL);
EOF;

$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {
echo “Table created successfully\n”;
}
$db->close();
?>[/php]

Then you would create a the guestbook itself by doing something like this:
[php]<?php
try {
/*** Connect to SQLite database ***/
$pdo = new PDO(“sqlite:database/guest_book.db”);
}
catch(PDOException $e)
{
echo $e->getMessage();
}

if ( isset($_POST[‘submit’]) && $_POST[‘submit’] == “Submit” ) {
/* SETUP query for connection to database table /
$query = ‘INSERT INTO guest_book(fname, lname, email) VALUES (:fname, :lname, :email)’;
/
Prepare the query /
$stmt = $pdo->prepare($query);
/
Execute the query */
$result = $stmt->execute(array(’:fname’ => $_POST[‘fname’], ‘:lname’ => $_POST[‘lname’], ‘:email’ => $_POST[‘email’]));

If ($result) {
	$message = "Data Successfully Inserted!";
} else {
	$message = "Error, something's not right!";
}

}

/* Display Guest Book /
$query = ‘SELECT id, fname, lname, email FROM guest_book ORDER BY id’;
/
Prepare the query /
$stmt = $pdo->prepare($query);
/
Execute the query */
$stmt->execute();

?>

Guest Book form { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; display: block; width: 100%; max-width: 400px; height: 400px; background-color: orange; padding: 10px; } fieldset.fieldsetStyle { border: 1px solid #fff; height: 360px; padding: 10px; } label.labelStyle, legend.legendStyle { font-family: Arial, Helvetica, sans-serif; font-size: 1.0rem; line-height: 1.5; color: #fff; }

legend.legendStyle { padding: 0 10px; }

input.inputStyle {
clear: right;
display: block;
width: 100%;
max-width: 200px;
height: 25px;
font-family: Arial, Helvetica, sans-serif;
font-size: 0.8em;
line-height: 1.0em;
color: #000;
padding: 0px 5px 0px 5px;
margin: 0px;
}

input.formBtn {
border: none;
outline: none;
background-color: #2e2e2e;
color: #fff;
width: 75px;
height: 25px;
margin: 20px 0;
}

p.record {
font-family: Arial, Helvetica, sans-serif;
font-size: 1.2rem;
line-height: 0.8;
}

<?php /* Create of loop of objects of guest_book table, example $record->fname is First Name in table */ while ($record = $stmt->fetch(PDO::FETCH_OBJ)) { ?>

<?php echo 'Record Number : ' . $record->id . ' Name : ' . $record->fname . ' ' . $record->lname . ' || Email Address : ' . $record->email; ?>

<?php } ?> <?php echo isset($message) ? $message : 'Guest Book'; ?> First Name Last Name Email Address
		<input class="formBtn" type="submit" name="submit" value="Submit">
		<input class="formBtn" type="reset" name="clear" value="Clear">
	</fieldset>
</form>
[/php]

Now this has no php sanitization or validation and that if you want to password protect you will have to use a full fledged database system (usually MySQL). This probably could be easily converted over using a text file, but since I don’t know text files too well I can’t help you there. I just felt like fooling around SQLite3 tonight and decided your post was a perfect for it. :wink:

and that if you want to password protect you will have to use a full fledged database system (usually MySQL)

Why?

My teacher doesnt want us touching MySQL for this project… I am only to be using strictly PHP.

And what i need help with, is i dont know how to be able to grab input from a form, save it into a text file, and then i need to be able to view the text file on the webpage which will be the “Guest book” that saves everyones info that submits it.

Grabbing the inputs would be similar in what I have done, but the only thing different is instead of a database the data would be save to a text file and read from a text file. Like I said while I could probably figure it out, but there are people here that can help faster and better than I could. I’m just not that familiar with text files.

You mostly wouldn’t for a simple guest book, like hacking into a guest book is going to do anything other than get a person’s email address. An I’m sure spammers get emails faster from different sources. ;D

Yes, exactly what i need it to do. Its a shame, because i dont really know much other than basic stuff, only been doing php for 2 months and doing for a required college class so my knowledge is slim.

This is the problem with college/uni, they don’t use real-world examples because for a guestbook - you wouldn’t use .txt files so already they’re teaching you bad habits.

As per your problem, take a look at this: http://stackoverflow.com/questions/14998961/php-write-file-from-input-to-txt

For reading the file, take a look at the file_get_contents command.

Well after fooling around with text files, I came up with this:
[php]<?php
/* A simple text file */
$file = “database/guest_book.txt”;
$record = array();

/* Save to the text file /
if ( isset($_POST[‘submit’]) && $_POST[‘submit’] == “Submit” ) {
/
Convert to a string, insert , and \n into the string /
$data = $_POST[‘fname’] . ‘,’ . $_POST[‘lname’] . ‘,’ . $_POST[‘email’] . “\n”;
/
Save to text file in directory database with file name guest_book.txt /
$result = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
/
Check Results of insert /
if ($result) {
$message = $result . ’ bytes written to file. ';
} else {
die(‘There was an error writing to this file’);
}
}
/
Grab each line of text file */
$records = file($file);

/* Explode line string into an array */
foreach ($records as $key => $value) {
$output[$key] = explode(",", $value);
}

/* Convert to associative inner array */
for ( $x = 0; $x < count($output); $x++) {
$record[$x][‘fname’] = $output[$x][0];
$record[$x][‘lname’] = $output[$x][1];
$record[$x][‘email’] = $output[$x][2];
}

?>

Guest Book form { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; display: block; width: 100%; max-width: 400px; height: 400px; background-color: orange; padding: 10px; } fieldset.fieldsetStyle { border: 1px solid #fff; height: 360px; padding: 10px; } label.labelStyle, legend.legendStyle { font-family: Arial, Helvetica, sans-serif; font-size: 1.0rem; line-height: 1.5; color: #fff; } legend.legendStyle { padding: 0 10px; } input.inputStyle { clear: right; display: block; width: 100%; max-width: 200px; height: 25px; font-family: Arial, Helvetica, sans-serif; font-size: 0.8em; line-height: 1.0em; color: #000; padding: 0px 5px 0px 5px; margin: 0px; } input.formBtn { border: none; outline: none; background-color: #2e2e2e; color: #fff; width: 75px; height: 25px; margin: 20px 0; } p.record { font-family: Arial, Helvetica, sans-serif; font-size: 1.2rem; line-height: 0.8; } <?php /* Loop through the records */ for ($y=0; $y < count($record); $y++) { /* Convert Inner Array to an object $entry where $entry->fname is first name of record */ $entry = (object) $record[$y]; /* Output the Record */ echo '

' . $entry->fname . ' ' . $entry->lname . ' || Email Address : ' . $entry->email . '

' . "\n"; } ?> <?php echo isset($message) ? $message : 'Guest Book'; ?> First Name Last Name Email Address [/php] I called it savingText.php and once again no sanitization or validation (that shouldn't be too much of a problem). An like I said I am no expert when it comes t working with text files, but going to php.net for that and other things works like a charm. There is probably even a simpler way of doing this with text files, but in my opinion this isn't real world practice. Using a database, even if it is SQLite3 is still the better way of doing it.

Oh when you first run the script, there might be a warning/error…just ignore it for the text file hasn’t be created yet or test it with an if-isset type of statement.

Thank you both for the help, ill see what i can do and get back to you with more help.

Thanks!

[php]

<title> Proccess Guestbook </title>
<?php if(isset($_POST['fname']) && isset($_POST['lname'])) { $data = $_POST['fname'] . '-' . $_POST['lname'] . "\n"; $ret = file_put_contents('guestbook.txt', $data, FILE_APPEND | LOCK_EX); if($ret === false) { die('There was an error writing this file'); } else { echo "$ret bytes written to file"; } } else { die('no post data to process'); } ?> [/php]

I am getting ‘There was an error writing this file’… not sure why…

I think but I could be wrong that

[php]if($ret === false) {[/php]

should be

[php]if($ret !== false) {[/php]

and you might want to check the directory that this particular file is in, to see if there was an text file called ‘guestbook.text’. You might just be getting a false positive anyways.

Good job, that worked… now my problem is outputting the text file to the webpage so i can see everyone that has submitted it.

/* Setup up Display */
[php]if (file_exists($file)) {

/* Grab each line of text file in an array */
$records = file(“guestbook.txt”);

/* Explode each line string in the array into an inner array */
foreach ($records as $key => $value) {
$output[$key] = explode("-", $value);
}

}[/php]

I don’t know if the above will work for I had to modify it a little bit to fit your code. Anyways, you can output it like such.

Just to demonstrate, hopefully that it works after the above portion of script is executed.

[php]for ($x = 0; $x < count($x); $x++) {
echo $output[$x][0] . “
\n”; // First Name:
echo $output[$x][1] . “
\n”; // Last Name:
}[/php]

I decide to post a separate post for the solution (well, my solution anyways ;D) for the looks of it that you want to come to the solution yourself. Can’t blame you for that is really the way to learn the material.

You can just look at the following for reference or if you get stuck. Or Not ;D

[php]<?php
/* A simple text file */
$file = “guest_book.txt”;
$record = array();

/* Save to the text file /
if ( isset($_POST[‘submit’]) && $_POST[‘submit’] == “Submit” ) {
/
Convert to a string, insert , and \n into the string /
$data = $_POST[‘fname’] . ‘,’ . $_POST[‘lname’] . ‘,’ . $_POST[‘email’] . “\n”;
/
Save to text file in directory database with file name guest_book.txt /
$result = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
/
Check Results of insert */
if ($result) {
$message = $result . ’ bytes written to file. ';
} else {
die(‘There was an error writing to this file’);
}
}

/* Setup up Display */
if (file_exists($file)) {

/* Grab each line of text file in an array */
$records = file($file);

/* Explode each line string in the array into an inner array */
foreach ($records as $key => $value) {
$output[$key] = explode(",", $value);
}

/* Convert to associative inner array */
for ( $x = 0; $x < count($output); $x++) {
$record[$x][‘fname’] = $output[$x][0];
$record[$x][‘lname’] = $output[$x][1];
$record[$x][‘email’] = $output[$x][2];
}

}
?>

Guest Book form { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; display: block; width: 100%; max-width: 400px; height: 400px; background-color: orange; padding: 10px; } fieldset.fieldsetStyle { border: 1px solid #fff; height: 360px; padding: 10px; } label.labelStyle, legend.legendStyle { font-family: Arial, Helvetica, sans-serif; font-size: 1.0rem; line-height: 1.5; color: #fff; } legend.legendStyle { padding: 0 10px; } input.inputStyle { clear: right; display: block; width: 100%; max-width: 200px; height: 25px; font-family: Arial, Helvetica, sans-serif; font-size: 0.8em; line-height: 1.0em; color: #000; padding: 0px 5px 0px 5px; margin: 0px; } input.formBtn { border: none; outline: none; background-color: #2e2e2e; color: #fff; width: 75px; height: 25px; margin: 20px 0; } /* Guest Book Display */ ul { border: 1px solid #2e2e2e; width: 500px; height: auto; padding: 10px 20px;} li { list-style: none; text-align: left;} a.record { font-family: Arial, Helvetica, sans-serif; font-size: 1.2rem; line-height: 1.5;
		text-decoration: none;
		color: #2e2e2e;
	}
	a.record:hover { color: blue; }
</style>
<?php echo isset($message) ? $message : 'Guest Book'; ?> First Name Last Name Email Address [/php]

Im confused, is that program you just made split up into 2 different webpages or is it supposed to be one link?

Because when the form is submitted it needs to output the text file, that program has a lot more bells and whistles… i need something very simple. I already have the form just need to output the input from the text file

[php]<?php
/* A simple text file */
$file = “guest_book.txt”;
$record = array();

/* Save to the text file */
if ( isset($_POST[‘submit’]) && $_POST[‘submit’] == “Submit” ) {

/* Convert to a string, insert , and \n into the string */

$data = $_POST[‘fname’] . ‘,’ . $_POST[‘lname’] . ‘,’ . $_POST[‘email’] . “\n”;

/* Save to text file in directory database with file name guest_book.txt */

$result = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);

/* Check Results of insert */

if ($result) {

$message = $result . ’ You have been registered into the Guest Book. ';

} else {

die(‘There was an error writing to this file’);

}
}

/* Setup up Display */
if (file_exists($file)) {

/* Grab each line of text file in an array */
$records = file($file);

/* Explode each line string in the array into an inner array */
foreach ($records as $key => $value) {

$output[$key] = explode(",", $value);
}

/* Convert to associative inner array */

for ( $x = 0; $x < count($output); $x++) {

$record[$x][‘fname’] = $output[$x][0];

$record[$x][‘lname’] = $output[$x][1];

$record[$x][‘email’] = $output[$x][2];
}

}
?>
[/php]

So this is what i have now, i used your code, and it is giving me an error message “There was an error writing to this file” so it doesnt even get past the first step… i didnt bother using your form as my is sufficient enough, however i really need to be able to view the “guest book” and see who has registered.

Sponsor our Newsletter | Privacy Policy | Terms of Service