Previous Page

Simple script to handle form info and add it to a database

NOTE: This is the very basic code to get information from a FORM and handle it with PHP then insert it into a database with MySQL. This will get that simple job done, but there are other ways to handle the users input before inserting it into a database (safely), so malicious users do not enter info into the form to damage your database through text manipulation.

I will cover that information later. This will get you comfortable with getting info and doing something with it so you can then, make a user-login-page to access this information. Bear with me...haha!

Click on the folling link to try it out.MySQL_Tuts/mysql_signup.php Then go to the MySQL_Tuts/mysql_login.php to see if it works.



You can insert the following code above the html portion of your new .php document

<?php
$name = "";     //variable to store their name
$username = ""; //variable to store their username
$password = ""; //variable to store their password

$alertMessage = ""; //variable to store a message - either an error or success.
					// NOTE: must set this equal to null for IF statement later in the script

if ($_SERVER['REQUEST_METHOD'] == 'POST')// if user clicks "Submit" button
{ 

	//====================================================================
	//	GET THEIR NAME, USERNAME, AND PASSWORD FROM THE FORM
	//====================================================================
		$name = $_POST['name']; // inside the single quotes is what the name =  for each field in the form
		$username = $_POST['username'];
		$password = $_POST['password'];
		
		// if user signing up doesn't fill in all fields - if any are "empty". You choose which they can leave empty below
		if(empty($_POST['name']) || empty($_POST['username']) || empty($_POST['password']))
		{
			$alertMessage = "Please fill in all fields.";
		}
		else // else connect and write to your database
		{
			//=============================================================
	        //	CONNECT AND WRITE TO YOUR DATABASE
			//=============================================================
					if ($alertMessage == "")// if no alert message, everything is good to go
					{
						//========================= Below is your database information from your host ===============================
						$db_User_Name = '**************';
						$db_password = '**************';
						$db_Database_Name = '**************';
						$db_Host_Name = '**************';
						//===========================================================================================================
						
						
						$database_connect = mysql_connect($db_Host_Name, $db_User_Name, $db_password);// try to connect to server
						
						$database_found = mysql_select_db($db_Database_Name, $database_connect);// try to connect to database
						
					} // no else statement here because the following IF statement will then be false and the Database cannot be found!
					
					if ($database_found)// if your database is found - excellent! do the following...
					{	
					
					//============================================== MYSQL PORTION OF THIS SCRIPT ============================================
					
					// NOTE: USE THE   `   SYMBOL NEXT TO THE   1 key  ON YOUR KEYBOARD FOR AROUND THE TABLE NAME AND THE FIELD NAMES BELOW.
					//       USE THE   '   SYMBOL NEXT TO THE   ENTER key	ON YOUR KEYBOARD FOR AROUND THE VARIABLES THAT YOU NEED. 
					
						 mysql_query("INSERT INTO `practice_table` (`name`, `username`, `password`)
						    VALUES ('$name','$password','$username')")  or die(mysql_error()); // place or die(mysql_error()) in here
																							   // incase the information doesn't get
																							   // inserted correctly into your database.
																							   // echo mysql_error(); later to check
																							   // Otherwise it may show that you successfully
																							   // inserted into your database, but nothing 
																							   // will be there. This error message will
																							   // give you a hint of where the problem is.
											   
						 mysql_close($database_connect);// You have now inserted the information from the form into your database.
						                                // So you can now close your database connection.
					//========================================================================================================================
					
											  
					     $alertMessage = "Thank you! You have successfully signed up.";// Everything went well to this point, so let the user
																				       // know that their information has been successfully entered.
					}
					else
					{
						$alertMessage = "Database cannot be found!";	
					}			
																													  
	    }// END else connect and write
}// END ------ ($_SERVER['REQUEST_METHOD'] == 'POST')
?>

Below is the html portion of this webpage. NOTE: Place this code inside the body tags


  <!-- Set the ACTION = to this same page since the php code to handle it is on this page -->
 <Form NAME ="form"  METHOD ="POST" ACTION ="../MySQL_Tuts/mysql_signup.php"> 
 	<table >

			<tr><td>Name:</td><td> <INPUT TYPE = 'TEXT' Name ='name'  maxlength="30"></td></tr>
			<tr><td>Username:</td><td> <INPUT TYPE = 'TEXT' Name ='username'   maxlength="30"></td></tr>
			<tr><td>Password: </td><td><INPUT TYPE = 'password' Name ='password'  maxlength="30" ></td></tr>
            
            <tr><td ><INPUT TYPE = "Submit" Name = "Submit" VALUE = "SIGN ME UP!"></td></tr>
	</table>
  </Form>
 

Below is the php to print any $alertMessages. You can place this where you want it to be seen in the body of your page

 
    
<?php
     echo $alertMessage;
	 echo mysql_error();// This will not print anything, unless the data does not INSERT into you database correctly
	
?>