Previous Page

Simple script to handle form info check if it exists in database

NOTE: This is the very basic code to get information from a FORM and handle it with PHP then check to see if the information exists in the database with MySQL. This will get that simple job done, but there are other ways to handle the users input before checking with the 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..

Click on the following link to try it out. MySQL_Tuts/mysql_login.php



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

<?php
$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
	//====================================================================
		
		$username = $_POST['username']; // inside the single quotes is what the name =  for each field in the form
		$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['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.    
					
					/*********** Check to see if their login credentials actually exsist in the datatbase  *****************/
					$SQL = " SELECT `id` FROM `practice_table` WHERE `username` = '$username' AND `password` = '$password' "
					        or die(mysql_error()); 
					$result = mysql_query($SQL);
					$num_rows = mysql_num_rows($result);
					
						if ($result)
		 				{
							if ($num_rows > 0)//if username and password are found the number of rows returned will be > 0
						    {
				                session_start();//start their login session
								$_SESSION['login'] = "1";//give the session a $_SESSION variable name  and set it = to something to pass to other pages
				
								//create a session start time
								$_SESSION['last_activity'] = time();// this variable will be checked on other pages to see if inactivity occurs
				 
								//get first name from database after login
								$alertMessage = "You have successfully logged in!";	
								
								mysql_close($database_connect);	//close the database connection			
		                    }
						    else
						    {
						  	 	$alertMessage = "Username/Password combination incorrect.";
						    }
						}
						else
						{
							$alertMessage ="Error logging in";	
						}
					}
					else
					{
						$alertMessage = "Database cannot be found!";	
					}
	   }
}
?>

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


 <p>Current users login below.</p>
<FORM NAME ="form1" METHOD ="POST" ACTION ="">

Username: <INPUT TYPE = 'TEXT' Name ='username'  value="" maxlength="40">
Password: <INPUT TYPE = 'password' Name ='password'  value="" maxlength="40">


<INPUT TYPE = "Submit" Name = "Submit1"  VALUE = "Login">
<br />
<!-- END OF CODE-->
 

Below is the php to print any $alertMessages. You can place this after the closing html tag or inside the body

 
<!-- output any alert message -->   
<?php
     echo $alertMessage;
	 echo mysql_error();// This will not print anything, unless the data does not INSERT into you database correctly
	
?>
<!-- END OF CODE -->