logo
Tutorials
Code examples
Courses
Dev Tips
Errors solved
Snippets
Technical writing program
AndroidAngularBeginnersBlockchainBootstrapCakePHPCode examplesCodeIgniterCoursesCSSDev TipsDjangoElectronErrors solvedFlaskFlutterGitGoLangGraphQlJavaJavascriptJqueryKotlinLaravelMachine LearningMySQLNodePhalconPHPPreactPythonReactReact NativeSnippetsspring bootSQLSvelteSymfonyTutorialsUncategorizedVue

PHP

How to Make Simple Login Form in PHP

Posted on: March 05, 2021 by Ariessa Norramli

In this article, you will learn how to make a simple login form in PHP.

Before following the example, you need to make sure that you have created a database name ‘codesource’, a table named ‘test’, a column named ‘username’ with type varchar(10) and another column named ‘password’ with type int(5). Then, insert the following data into the table.

Make Simple Login Form

In order to make a simple login form, you can use the mysqli_query() method and mysqli_fetch_array() method.

<html>
<body>
	<div class="container">
    		<form method="post" action="">
        		<div id="div_login">
            			<h1>Login</h1>
            			<div>
                			<input type="text" class="textbox" id="username" name="username" placeholder="Username" />
            			</div>
            			<div>
                			<input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
            			</div>
            			<div>
                			<input type="submit" value="Submit" name="submit" id="submit" />
            			</div>
        		</div>
    		</form>
	</div>

	<?php
		// Start a PHP session
		session_start();

		// Host name
		$host = "localhost";

		// User
		$user = "root";

		// Password
		$password = "";

		// Database name
		$db = "codesource";

		$connection = mysqli_connect($host, $user, $password, $db);

		// If the connection fails
		if (!$connection) {

			// Display message and terminate script
  			die("Connection failed: " . mysqli_connect_error());
		}

		// If the submit button is pressed
		if(isset($_POST['submit'])){

			// Escape special characters in a string
    			$username = mysqli_real_escape_string($connection, $_POST['username']);
    			$password = mysqli_real_escape_string($connection, $_POST['password']);

			// If username and password are not empty
    			if ($username != "" && $password != ""){

				// Query database to find user with matching username and password
        			$query = "select count(*) as cntUser from users where username='".$username."' and password='".$password."'";

				// Store query result
        			$result = mysqli_query($connection, $query);

				// Fetch row as associative array
        			$row = mysqli_fetch_array($result);

				// Get number of rows
        			$count = $row['cntUser'];

				// If number of row is more than zero
        			if($count > 0){

					// Set matched user as current user
            				$_SESSION['uname'] = $username;

					// Display success message
	    				echo "You are logged in!";

				// Else if number of row is less than zero
        			} else {
					
					// Display failed message
            				echo "Error! Invalid username and password.";
        			}

    			}

		}
	?>
</body>
</html>

Initial Login Form

Successful Login

Failed Login

Note: The mysqli_query() method functions by executing a query on the database. In this example, mysqli_query() method is used to search for rows that matches the username and password supplied in the login form. The mysqli_fetch_array() method functions by fetching a result row as an associative array.

Related Posts:

  • Setting Up Angular Authentication Using JWT
  • Building a blogging platform Using React, GraphQL, And…
  • Setting up Vue Authentication using Expressjs, MongoDB, and…
  • Build a CRUD Application with Hasura and Vue-Apollo
  • Using Firebase Authentication in a Vue Application
  • Getting started with Writing Test In Vue Applications
  • Building the login system with PHP 7.3.3 and MySQL
  • Build A Blog App with ExpressJs and SvelteJs
  • Create a Sleek Note app With Flutter
  • Building a Twitter Clone Using JQuery
  • Build a Note Taking Application using Kotlin
  • Build a CRUD application using CodeIgniter 4 and Mysql
  • Handling Vue Authentication using GraphQL API
  • Building an E-Commerce app with Vue.js, Vuex & Axios
  • Laravel file upload tutorial – Handling File Uploads in…
  • Brief Overview Of Design Pattern Used in Laravel
  • Laravel eloquent relationships explained
  • Create A Password Strength Calculator using Kotlin
  • Authenticating React App with Firebase
  • Build a Simple Blog using Axios With React

category :

Code examples

tag :

php

Share on social media

//
PreviousNext
Ariessa Norramli

About the author

Ariessa Norramli
Programmer | Writer | bitsized dot me at gmail dot com
See all posts

Useful front-end & UX tips, delivered once a week.

Useful front-end & UX tips, delivered once a week. 🎁




Dev Tips

How To Create NFT Ar

January 14, 2022

How To Create NFT Art With No Coding Experience​

Collection of the 20

October 13, 2021

Collection of the 20 useful Python Scripts

No Code Development

October 1, 2021

No Code Development As An Alternative For Programming

Top 4 Best Programmi

August 4, 2021

Top 4 Best Programming Languages for Beginner

How to prepare for a

July 16, 2021

How to prepare for a Data Science interview?

Code Examples

How to concatenate t

March 3, 2022

How to concatenate two lists in python

How to use math.log(

March 3, 2022

How to use math.log() function in Python

How to add a new ite

March 2, 2022

How to add a new item to a python dictionary

How to use switch st

March 2, 2022

How to use switch statement in React

How to use whereIn()

February 23, 2022

How to use whereIn() method in Laravel

Errors Solved

How to fix module no

February 4, 2022

How to fix module not found: can’t resolve in React

How to fix Vscode in

February 2, 2022

How to fix Vscode indentation

How to fix MongoErro

December 24, 2021

How to fix MongoError:e11000 duplicate key error collection

How to fix vue packa

December 24, 2021

How to fix vue packages version mismatch

How to fix typeerror

December 24, 2021

How to fix typeerror: $ is not a function in JavaScript

Contact
Guest writing
Copyright
Privacy
Dunebook
Learn React and React Native
AndroidAngularBeginnersBlockchainBootstrapCakePHPCode examplesCodeIgniterCoursesCSSDev TipsDjangoElectronErrors solvedFlaskFlutterGitGoLangGraphQlJavaJavascriptJqueryKotlinLaravelMachine LearningMySQLNodePhalconPHPPreactPythonReactReact NativeSnippetsspring bootSQLSvelteSymfonyTutorialsUncategorizedVue

© 2022 Codesource.io