Jump to content

First Attempt at PHP!


Mark H

Recommended Posts

Hi all,Many thanks to all the guys who have helped me with getting some php going.I have now done most of my coding for an online petition, and have the form structure done. I've got some parts to add, such as the exit if not UK, and I haven't yet tested on a server.I've put the code I've written below (a good portion of this is credited to justsomeguy, as his tutorial was amazingly helpful! Thanks!)If anyone has the time to look through this for errors I'd appreaciate it! No worries if it's too much. :)

<?phpsession_start();require_once 'db.php';$page_mode = isset($_POST['page_mode']) ? $_POST['page_mode'] : '';$error_string = '';if ($page_mode == 'signed'){  // process form	if ($UK == 'nonuk')	{		// exit and flag reason	}	else{  $firstname = trim($_POST['firstName']); // trim to remove whitespace  $lastname = trim($_POST['lastName']); // trim to remove whitespace  $email = trim($_POST['email']); // trim to remove whitespace  $postcode = trim($_POST['postcode']); // trim to remove whitespace}function isValidEmail($email = ''){	return preg_match("/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix",$email);if (!isValidEmail($email))	$error_string .= 'Please enter a valid email address.<br>';  if ($firstName == '')	$error_string .= 'Please enter your name.<br>';	  if ($firstName == '')	$error_string .= 'Please enter your name.<br>';		 if ($postcode == '')	$error_string .= 'Please enter your postcode.<br>';	if ($error_string == '')  {	$result = db_query("SELECT id FROM users WHERE email='" . mysql_real_escape_string($email) . "'");	if (mysql_num_rows($result) > 0)	  $error_string .= 'This email address has already signed the petition.<br>';	else	{	  $email = mysql_real_escape_string($email); // protect against SQL attacks	  $firstName = mysql_real_escape_string($firstName);	  $lastName = mysql_real_escape_string($lastName);	  $postcode = mysql_real_escape_string($postcode);	  	  if ($subscribe == "1")	  {		  require_once 'mail_list_db.php'		  db_query ("INSERT INTO rabel (email) VALUES ('($email)')");	  }	  db_query("INSERT INTO users (firstName, lastName, email, postcode) VALUES ('{$firstName}', '{$lastName}', '{$email}', '{$postcode}')");	  header('Location: thankyou.php');	  exit();	}  }	?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">

And my form looks like:

<h2>Rabel Petitions - Freedom of Speech:</h2>    <div id="form">      <div class="error_text"><?php echo $error_string; ?></div>      <form id="fos1" name="fos1">        <form action="freedom-of-speech.php" method="post">    <input type="hidden" name="page_mode" value="signed">        <p>          <label>Your First Name:            <input type="text" name="firstName" id="firstName" size="30" maxlength="50" value="<?php if (isset($firstName)) echo $firstName; ?>"/>          </label>        </p>        <p>          <label>Your Last Name:              <input type="text" name="lastName" id="lastName" size="30" maxlength="50" value="<?php if (isset($lastName)) echo $lastName; ?>"/>          </label>        </p>        <p>          <label>Your Email Address:            <input type="text" name="email" id="email" size="30" maxlength="255" value="<?php if (isset($email)) echo $email; ?>"/>          </label>        </p>        <p>          <label> Enter your Postcode:            <input type="text" name="postcode" id="postcode" size="15" maxlength="10" value="<?php if (isset($postcode)) echo $postcode; ?>"/>          </label>        </p>        <table width="265">          <tr>            <td><label>              <input type="radio" name="UK" value="uk" id="UK_0" />              I am a UK citizen aged 18 or over</label></td>          </tr>          <tr>            <td><label>              <input type="radio" name="UK" value="nonuk" id="UK_1" />              I am not a UK citizen aged 18 or over</label></td>          </tr>        </table>        <p><strong>I hereby sign the petition:           <input type="checkbox" name="sign" id="sign" />        </strong></p>        <p>Check here if you want to receive <br />email updates from Rabel:           <input type="checkbox" name="subscribe" id="subscribe" />        </p>        <p>          <input type="submit" name="submit" id="submit" value="Submit" />        </p>        <p> </p>      </form>    </div>

Link to comment
Share on other sites

Bad business here:<form id="fos1" name="fos1"><form action="freedom-of-speech.php" method="post">And why does the PHP script not test whether all the POST variables are set? Eg: $_POST['firstName']

Link to comment
Share on other sites

If anyone has the time to look through this for errors I'd appreaciate it! No worries if it's too much. :)
you should look into downloading an AMP (Apache, MySQL, PHP) stack, which they offer for Windows (WAMP) or Mac (MAMP) as it will let you test test locally (on your own machine) without needing to upload to a server. Combined with turning error reporting on in your PHP scripts, you can see if there are any errors in your code and test it all locally before deploying it live.
Link to comment
Share on other sites

Bad business here:<form id="fos1" name="fos1"><form action="freedom-of-speech.php" method="post">And why does the PHP script not test whether all the POST variables are set? Eg: $_POST['firstName']
I am trying to find out about the form id and form name attributes and can't find them listed in the reference section.Would you advise dropping these altogether?Thanks,Mark.
Link to comment
Share on other sites

What I think DD was trying to get is that it should all be in one <form> tag, not split over two.http://www.w3schools.com/tags/tag_form.asp
Ah yes! I see now. Easy to sort. Thanks.Also, will be adding the checks to make sure all the fields have been entered.Thanks guys,Mark. :)
Link to comment
Share on other sites

One thing I am not clear on is my accessing, potentially, 2 diffrent databases.The first db (db.php) is accessed at the start of my code. Then I insert:

if ($subscribe == "1")	  {		  require_once 'mail_list_db.php'		  db_query ("INSERT INTO rabel (email) VALUES ('($email)')");	  }	  db_query("INSERT INTO users (firstName, lastName, email, postcode) VALUES ('{$firstName}', '{$lastName}', '{$email}', '{$postcode}')");	  header('Location: thankyou.php');	  exit();

At this point two databases are in action: are there any issues with this?Thanks,Mark.

Link to comment
Share on other sites

You're saying that table rabel and table users are in different databases? If you're using mySql, mysql_query would require a second argument that specifies which database to use. The argument would be the resource returned by mysql_connect. Your db_query is not familiar to me, so I don't know what to tell you.

Link to comment
Share on other sites

You're saying that table rabel and table users are in different databases? If you're using mySql, mysql_query would require a second argument that specifies which database to use. The argument would be the resource returned by mysql_connect. Your db_query is not familiar to me, so I don't know what to tell you.
Ah, maybe it should read mysql_query? Not db_query.I'll take some time to look into this a touch more.Mark.P.S. yes, table rabel is in a different database to table users.rabel is my mailing list, but what I need to do also is check with my host how the mailing lists work...if they don't use a MySQL database I'm wasting my time!
Link to comment
Share on other sites

If you need to access multiple database connections at once, then you can create multiple MySQL connection resources.

$c1 = mysql_connect(...);mysql_select_db($c1, "database_1");$c2 = mysql_connect(...);mysql_select_db($c2, "database_2");mysql_query("SELECT FROM table1", $c1);mysql_query("INSERT INTO table2", $c2);

Link to comment
Share on other sites

Uhm... does the code even work? First of all, I see you're checking for a $UK variable, which is not defined anywhere else (so, as far as I can tell, it has no values). Next, you start defining isValidEmail by using a curly bracket. But then you treat it as a single-line function and don't close the bracket, so the rest of the code should be part of the function. And the fact that you do not close the bracket should throw an error.Or... I might be missing something.

Link to comment
Share on other sites

No, you're not missing something: the area os isValidEmail should be closed, and then I should go on to check the other variables..an error on my part.The $UK variable comes from the radio buttons in the form. Yet having looked, I haven't brought that into the PHP code, which I need to do.Thanks,Mark.P.S. This is my first, rough, attempt. I am sure the code won't work, but I wanted to spot any major flaws that a newbie like me could make before I progressed any further. I still have quite a bit to add to the code, but if I can get what I have done so far "mended", it will help me not to make the same obvious mistakes. Thanks.

Link to comment
Share on other sites

In this case, you'd do something like

if(isset($_POST['UK'])) {	$uk = $_POST['UK'];} else {	$uk = NULL;}

And then run your checks.

Link to comment
Share on other sites

Okay, I've made some adjustments. It's still not complete, but it should now be clear where I have made notes of what I still need to add.DD, the code doesn't check if all the fields have been set, as if any of them return a ' ' it will bring up one of the error_strings.

<?phpsession_start();require_once 'db.php';$page_mode = isset($_POST['page_mode']) ? $_POST['page_mode'] : '';$error_string = '';if ($page_mode == 'signed'){  // process form	$subscribe = isset($_POST['subscribe']);		$uk = isset($_POST['UK']);		if ($uk == 'nonuk')	{		$error_string = 'Only UK citizens who are 18 or over may sign this petition';	}{  $firstname = trim($_POST['firstName']); // trim to remove whitespace  $lastname = trim($_POST['lastName']); // trim to remove whitespace  $email = trim($_POST['email']); // trim to remove whitespace  $postcode = trim($_POST['postcode']); // trim to remove whitespace}function isValidEmail($email = ''){	return preg_match("/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix",$email);if (!isValidEmail($email))	$error_string .= 'Please enter a valid email address.<br>';}if ($firstName == '')	$error_string .= 'Please enter your first name.<br>';if ($lastName == '')	$error_string .= 'Please enter your last name.<br>';if ($postcode == '')	$error_string .= 'Please enter your postcode.<br>';if ($error_string == '')  {	$result = db_query("SELECT id FROM users WHERE email='" . mysql_real_escape_string($email) . "'");	if (mysql_num_rows($result) > 0)	  $error_string .= 'This email address has already signed the petition.<br>';	else	{	  $email = mysql_real_escape_string($email); // protect against SQL attacks	  $firstName = mysql_real_escape_string($firstName);	  $lastName = mysql_real_escape_string($lastName);	  $postcode = mysql_real_escape_string($postcode);	  	  if ($subscribe == "subscribe")	  {		  // subscribe to mailing list	  }	  mysql_query("INSERT INTO users (firstName, lastName, email, postcode) VALUES ('{$firstName}', '{$lastName}', '{$email}', '{$postcode}')");	  header('Location: thankyou.php');	  exit();	}  }}?>

I am almost at the place where I can check this on my server, but not quite!Thanks for all the corrections so far guys, I'm far better learning "live" like this than tutorials only.

Link to comment
Share on other sites

Uhm... in the code above, $uk is either true or false, based on the return value of the isset(), so

$uk = isset($_POST['uk']);if($uk == 'nonuk') {}

should not do much. What you want to do is similar to $page_mode.

$uk = isset($_POST['uk']) ? $_POST['uk'] : '';

It's more of a matter of style, but I prefer storing the error messages as array values, and then printing them with a foreach loop, surrounding the errors with <p></p>

$errors = array();$errors[] = 'Please enter your username';// Codeforeach($errors as $error) {	 printf("<p>%s</p>\n", $error);}// Code

I also suggest you install an AMP stack for your operating system and test your scripts there, eventually with error reporting set to E_ALL | E_STRICT. This will help you write very good code.

Link to comment
Share on other sites

Thanks IP...I've just downloaded a testing server.I'll correct the bit of code you suggested.For now, I'll stick with the error messages as they are. Maybe in due course I'll look at alternative ways.Mark.

Link to comment
Share on other sites

DD, the code doesn't check if all the fields have been set, as if any of them return a ' ' it will bring up one of the error_strings.
Yes, I can read. :)What you may not realize is that when PHP encounters a variable that has not been set (for most developers, this is a form variable) the interpreter issues a warning. This is not as serious as an error, so execution does not stop, but it is still a signal that something has gone wrong.You do not see the warnings because your error reporting is switched off. But they are there all the same.Good programmers eliminate the potential for warnings as well as errors. Compared to the time it takes to write and debug an application, the time it takes to write a few isset() statements is trivial. I suspect you came here to learn to do what is best. Protecting your code against warnings is best.
Link to comment
Share on other sites

Thank you DD...yes, of course, the best way of coding is what I want! Thank you. You're right, it's not a great deal of time to add the isset statements, and is "meet", as one might say.Thank you also justsomeguy for the necessary code to check errors. It may well be that I get this code sorted enough to test on server today!Mark.

Link to comment
Share on other sites

Thing is... you can't just "blindly copy techniques" people suggest in here. Coming with a piece of code and asking what's wrong is not the best way to learn. As I said earlier, download an AMP stack and run the code in the first post. It will surely generate errors. Fatal or warnings, or notices. It doesn't matter. Read the errors, understand them, and then come up with a fix. Make them disappear. Debugging is where you're going to spend most of your time when writing an application, so you don't have to get everything right at first.For example, when I first learnt PHP, I was presented the concept of sticky forms. The code there was something like

<input type="text" name="username" id="username" value="<?php echo $username; ?>" />

and I was running it locally, without having PHP print warnings on screen. Some day, I switched to E_ALL | E_STRICT, displaying all the illegalities on screen and saw that my field was already filled with a warning. I read the error and figured out that, when you first display the page, $username is not set. So it was easy to fix that by writing a condition.

<input type="text" name="username" id="username" value="<?php if(isset($username)) echo $username; ?>" />

Link to comment
Share on other sites

Thanks IP.I've now tested on a server..a few bugs to correct but now it is working fine!I can't seem to get the WAMP working though? In the end I uploaded to a testing directory on my host.I like to learn on a number of levels...the tutorials are great, but I also find a help to have basic errors pointed out. The debugging is fine, but initially I wanted to get some "person" feedback.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...