Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Mal

macrumors 603
Original poster
Jan 6, 2002
6,253
30
Orlando
OK, so in my years of (light) web development, I've played around with many things, but one of the things I've never been able to wrap my head around so far is forms. I can do the front end stuff, that's easy. I just can't figure out how to do a backend form handler.

To be more specific, what I'd like to do right now is create a form to capture First and Last Name and Email Address, then feed them into a database. I'm thinking either go simple and put them directly into a CSV file, or go more complex but more secure and put them into a MySQL database and write a script that can generate a CSV from that database on the fly.

Can anyone help me figure out how to do that? Assume that other than the HTML code to create the form itself, I'm totally ignorant of anything related to this (it's very close to the truth).

jW
 
Searching out tutorials is your best bet, like this one. FYI, whether you write directly to a CSV or to a database, both are equally secure (or insecure). Adding security would involve encrypting the data and the HTTP traffic between the page the and the visitor. For what you're currently doing, encryption isn't needed.

The backend can be done with any of several languages including PHP, Perl, Python, Ruby, C, etc. The link above is using PHP. I'd suggest PHP on the basis that you'll find loads of tutorials and information to help you on this task. So try getting through some tutorials and see how far you get. If something stumps you, just post back and we'll help you out.

Some searches you may want to try: "php form processing" "php store form database" "mysql export csv"
 
Thanks for the link, I'll check that out. I would agree that PHP is my best choice, because I have done some work in it (modifying code, not generating original code, however) so I have more familiarity with it. When you say encryption isn't needed for what I'm doing, is it simply your opinion that the data being processed doesn't need to be securely transmitted? I'm fine with that if that's the case, makes my job easier. Of course, it'll be up to the site owner.

jW
 
The reason I don't think the encryption is needed is because the data you're transmitting isn't sensitive. If they were logging into the system or asking for SSN or credit cards numbers, then that stuff would definitely need to be encrypted. Just having names and emails addresses generally isn't enough to get worked up about though, most of the time. Doing the encryption thing can be a hassle too, setting up SSL and paying for certificates and all that, though there are some easier (though lesser secure) methods out there.
 
OK, so after looking around at the options and methods, I decided to try HTML_QuickForm. As I knew I would, I apparently didn't do something right.

My hosting (SiteGround.com) includes PEAR already installed, but not the HTML_Quickform module. They provide instructions (http://www.siteground.com/tutorials/php-mysql/pear_modules.htm) which I followed exactly to install the module. I placed the php.ini file they told me to create in both the directory of this website and the parent directory just in case, since it did say all directories. When I insert the form using the following code:

Code:
<div id="form">
		<?php
		  require_once "QuickForm/QuickForm.php";
		
		  $form = new HTML_QuickForm('reg');
		  
		  $form->setDefaults(array(
		  		'name' => 'Your Name'
		  ));
		
		  $form->addElement('header', null,
		                    'Register here to win a $25 iTunes Gift Card!');
		  $form->addElement('text', 'name',
		                    'Name:', array('size' => 50, 'maxlength' => 255));
		  $form->addElement('text', 'email',
							'Email:', array('size' => 50, 'maxlength' => 255));
		  $form->addElement('submit', 'btnSubmit',
		                    'Submit');
		                    
		  $form->applyFilter('name', 'trim');
		  $form->AddRule('name', 'Please enter your name', 'required', null, 'client');
		  $form->AddRule('email', 'Please enter your email address', 'required', null, 'client');
		  
		  if ($form->validate()) {
		  	echo '<h1>Thank you, ' . htmlspecialchars($form->exportValue('name')) . '!</h1>';
		  	exit;
		  }
		
		  $form->display();
		?>
</div>

I get the following output:

Code:
 Warning: main(PEAR.php) [function.main]: failed to open stream: No such file or directory in /home/japancpi/pear/QuickForm/QuickForm.php on line 29

Fatal error: main() [function.require]: Failed opening required 'PEAR.php' (include_path='.:/usr/lib/php:/usr/local/lib/php:/home/japancpi/pear') in /home/japancpi/pear/QuickForm/QuickForm.php on line 29

(japancpi is the proper username, btw, though this is not the end destination, I'm simply testing it on another server I own.)

Help?!

jW
 
[removed part about installing pear.php]


Honestly though, creating the back end for a form is very simple...

Code:
<?php
$username = $_POST['name']; 
?>

That code get the post data from your form, finds the field where
Code:
<input name="name" />
or any other input type: buttons, boxes, textarea, etc...
and stores it for whatever you are going to do with it.

Since im not sure exactly what you mean to do with the data just yet this is all I can offer.
 
How would I go from that (if I don't need QuickForm, that might be better anyways) to a .CSV file?

jW
 
Here's a simplistic way, though really you should be scrubbing the data (validating it) in some way before processing it too much.
PHP:
$name = $_POST['name'];
$email = $_POST['email'];
$fw = fopen("your.csv", "a"); // opens file for appending data to end of file
fwrite($fw, "$name, $email\n");
fclose($fw);

PHP fopen function
 
Hey, cool. That's what I was looking for. Now, how to validate the data? All I need to do really is make sure they're not null and that the email address contains an @ symbol. We're not expecting a high rate of registration, so we can scrub the data manually after we grab the CSV file. We'll probably grab it at regular intervals and then delete the existing data so it doesn't grow large and the data can't be earily grabbed by someone.

jW
 
Here's some regular expressions I use for this type of validation. For the name I only check if it was not provided. Not sure how strict you would want to be on this.

PHP:
$name = trim($_POST['name']); // trim will cut of spaces at beginning or end of string
$email = trim($_POST['email']);

$error = false;
$error_msg = "";

if ($name == "") {
  // didn't supply a name
  $error = true;
  $error_msg += "<li>You did not supply a name!</li>";
}
$regEmail = '/^[\w\.\+_\-]+[\w]+@(([\w\.\-]+)\.)[a-zA-Z]{2,6}$/';
if (!preg_match($regEmail, $email)) {
  // the email address is not in the right format
  $error = true;
  $error_msg += "<li>The email you provided does not appear valid!</li>";
}
if ($error) {
  echo "<h1>Errors Found!</h1>";
  echo "<ul>$error_msg</ul>";
}
// if no errors found, write out csv file
else {
  $fw = fopen("your.csv", "a"); // opens file for appending data to end of file
  fwrite($fw, "$name, $email\n");
  fclose($fw);
  echo "<h1>Success!</h1>";
}
 
Ok, so I added that code, and the form doesn't post any data to the CSV file except a comma and then a new line. Any thoughts?

BTW, that's not a comment on the error checking code, it didn't work before that code was added.

jW

EDIT: Nevermind, I forgot the method attribute in the form itself. Thanks so much everyone! You've been incredibly helpful, I think I actually understand what you gave me even though I couldn't have come up with it before.
 
Ok, so I added that code, and the form doesn't post any data to the CSV file except a comma and then a new line. Any thoughts?

BTW, that's not a comment on the error checking code, it didn't work before that code was added.

jW

Can you post the HTML and PHP you're using?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.