irwan

PHP Basic : Adding form elements to MySQL

Nov 20th, 2011
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.11 KB | None | 0 0
  1. Create form :
  2.  
  3. <form name="addPerson" action="addPerson.php" method="post">
  4.   <div>First Name:</div>
  5.   <div><input type="text" name="firstName" size="40" maxlength="255" /></div>
  6.  
  7.   <div>Last Name:</div>
  8.   <div><input type="text" name="lastName" size="40" maxlength="255" /></div>
  9.  
  10.   <div>Email Address:</div>
  11.   <div><input type="text" name="email" size="40" maxlength="255" /></div>
  12.  
  13.   <div>Phone Number:</div>
  14.   <div><input type="text" name="phone" size="40" maxlength="255" /></div>
  15.  
  16.   <div><input type="submit" value="Add Person" /></div>
  17. </form>
  18.  
  19.  
  20. Get and View Information :
  21.  
  22. <?php
  23.    //get the form items.
  24.   $firstName = addslashes(htmlspecialchars($_POST['firstName']));
  25.   $lastName = addslashes(htmlspecialchars($_POST['lastName']));
  26.   $email = addslashes(htmlspecialchars($_POST['email']));
  27.   $phoneNum = addslashes(htmlspecialchars($_POST['phone']));
  28.  
  29.   //this will be for the error message to display
  30.   //if they didn't fill out the form completely.
  31.   $errorMessage = "";
  32.  
  33.   if(empty($firstName)) $errorMessage .= "You didn't enter a First Name<br/>";
  34.   if(empty($lastName)) $errorMessage .= "You didn't enter a Last Name<br/>";
  35.   if(empty($email)) $errorMessage .= "You didn't enter an Email Address<br/>";
  36.   if(empty($phoneNum)) $errorMessage .= "You didn't enter a Phone Number<br/>";
  37.  
  38.   //now we check to see if there was an error
  39.   if(empty($errorMessage)) {
  40.     //everything is alright and we can now add it to the DB
  41.  
  42.     //these variables are used for database connection
  43.     $host = "localhost";
  44.     $user = "db_user";
  45.     $pass = "db_pass";
  46.     $database = "db_name";
  47.  
  48.     //connect to the database.
  49.     $db = mysql_connect($host, $user, $pass);
  50.     mysql_select_db ($database);
  51.  
  52.     //set up the query to add the information.
  53.     $query = "INSERT INTO 'people' ('firstName', 'lastName', 'email', `phone`)
  54.       VALUES ('$firstName', '$lastName', '$email', '$phone');";
  55.     $result = mysql_query($query) OR die(mysql_error());
  56.  
  57.     echo 'You have successfully added ' . $firstName . ' to the database!';
  58.   } else {
  59.     //something was wrong.
  60.     echo $errorMessage;
  61.   }
  62. ?>
  63.  
Advertisement
Add Comment
Please, Sign In to add comment