PHP form Registration script with mysql database entry

PHP form Registration script with MySQL database

PHP form Registration script with Database [mysql]  is a requirement of every web app that takes user data and uses it for further processing according to the need.

I created such form with PHP MySQL database which can be copied for use from below given lines.This code script works properly with PHP 7.1 and MySql5. I created it on my local machine running on Windows.But for a live server, I always prefer UBUNTU Linux.I moved from MySql_* function to PDO extension so don’t worry about it, it going to work fine if you use old MySql_* functions or MySqli extension.

It is the first step to creating a Registration form for your very first web application.When it comes to PHP I called it PHP registration form.If you want to add file upload functionality to the registration from then get PHP file upload code with database script and modify according to your requirement.

PHP form registration script with MySql Database requirements:

  1. HTML Form
  2. MySql Database
  3. PHP Registration Script
  4. DataCheck PHP script

Getting started: Step1- Create an HTML Form For Registration

Every Registration form required HTML form.Create an HTML form with Method POST.POST method is more secure than GET method because no visible information appears in browser’s address bar.Add action, Register.php[ registration script]. Register.php handle the form and process data for make entries into the database. below is a given form code you can copy.

<form method="post" action="index.php">
Email:<input type="email" name="email1" placeholder="Email@provider.com"><br>
Re Enter Email: <input type="email" name="email2" placeholder="Email@provider.com"><br>
Name: <input type="text" name="name" placeholder="Enter your Name"><br>
Password: <input type="Password" name="Password" placeholder="***************"><br>
 <input type="submit" name="go" value='SignUP'>
</form>

 Step2: Create a MySql Database [test]

This script required MySql database with PDO Extension. It is not required you can do it by simply using MySqli or MySql_*functions. For This script, I am using database name “test” on my local machine.I use table “users” from test database. I have exported my table to users.sql for better understanding. You can import bellow given users.sql to your own database.

Users.sql

-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 02, 2017 at 12:02 PM
-- Server version: 5.7.14
-- PHP Version: 5.6.25

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
 `id` int(10) NOT NULL,
 `email` varchar(250) NOT NULL,
 `password` varchar(50) NOT NULL,
 `name` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `email`, `password`, `name`) VALUES
(1, 'websitemaker001@gmail.com', 'admin', 'admin'),
(2, 'hypertext001@gmail.com', 'password', 'admin'),
(6, 'pradeepbhardwaj4@gmail.com', 'password', 'admin'),
(7, 'abc@gmail.com', 'password', 'admin'),
(8, 'a@gmail.com', 'password', 'admin'),
(9, 'b@gmail.com', 'password', 'admin');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
 MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step3: PHP form registration script

I assume that you have created Database and imported table users.sql to your own MySql database. Now you are ready to create register.php That will handle all your form data and process it for making entries to the database.Recheck your HTML form and make sure your action is set to register.php.You can create a copy of register.php script from bellow given code.

Register.php

<?php
session_start();
error_reporting(0);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$Name=$_POST['name'];
$Password=$_POST['Password'];
$go=$_POST['go'];
if(isset($go)){
 if ($email1!="" and $email2!="" and $Name!="" and $Password!="") {
 if ($email1===$email2) {
 $db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '');
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
 $stmt = $db->query("SELECT * FROM users where email='$email2'");
 $row = $stmt->rowCount();
 if ($row > 0){
 $message="Email is alrady registered with us try logging in.";
 }
 else{
 $stmt = $db->prepare("INSERT INTO users(email,password,name) VALUES(:field1,:field2,:field3)");
 $stmt->execute(array(':field1' => $email1, ':field2' => $Password, ':field3' => $Name));

 $message="<h1 style='color:green'>You are successfully registered with US lets go to user.php</h1>";
 $_SESSION['user']="$email1";
 header( "refresh:2;url=user.php" );
 }

 }
 else{
 $message="Email miss match.. Kindly type email carefully";
 }
 }else{
 $message="please Fill all form fields";
 }
}


?>
<?php echo "<h1>$message </h1>"; ?>

 

The first function is used for the session, if we get all the condition true then we store user id or email to the session  for sending users on user account page.All the data is collected by using POST method.We check fields for empty strings and then make sure that both entered email are same and not already present in the database. If all the condition meets true, the script store email to the session and create an entry to the database regarding submitted information.

Step4: Data check PHP script

Datacheck PHP script is just for checking all data from your database.It checks that Register.php working fine or not. IT puts all table data in the form of HTML table.

check.php

<?php
session_start();
//error_reporting(0);
echo "<table>";
echo "<th> <tr> <td><b>#ID</b> </td><td><b>Email</b> </td><td><b>Name</b></td><td><b>Password</b> </td> </tr> </th>";
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '');
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
 $stmt = $db->query("SELECT * FROM users");
 $result=$stmt->setFetchMode(PDO::FETCH_ASSOC); // ok with value 1
 foreach($stmt->fetchAll() as $v){
 $id=$v['id'];
 $email=$v['email'];
 $name=$v['name'];
 $pw="N/A";
 echo "<tr> <td>$id </td><td>$email </td><td>$name</td><td>$pw </td> </tr>";

 }
 
 
 echo "</table>"; 
 

?>

This is all done!

Read also: PHP file upload script with database and gallery

Get any problem regarding these codes? let’s discuss here bellow into the comment box.

PHP file Upload full code with database advance script examples Demo

PHP file Upload script with Database

Every Blog and website require file upload functionality for the different purpose.I created a PHP file upload script demo for the beginner using procedural programming using PHP.It’s free to use, anyone can use it for their websites.Today almost 80% sites are powered by PHP this is the reason  PHP file upload script exist on my site.

PHP file upload script requirements:

  1. Uploads directory
  2. HTML form
  3. MySql database
  4. PHP upload script
  5. PHP view script

Getting started: Step1- Uploads directory

Create a  uploads directory where your all PHP file are stored.This directory is used by the upload.php script to store uploaded files/images.All the uploaded files are stored into tmp directory for any session of file uploading.Then letter these file moved to uploads directory by upload.php script.

Step 2:HTML form

Html form is used for getting a file from client side and send it to the upload handler [upload.php].For a file upload form must have the method set to Post and enctpye set to multipart/form-data and action set to Handler script in my case it is upload.phpFor file upload at least one input element required with type=”file”. Below I have given an example of HTML form for file upload in index.html.

Index.html



<!DOCTYPE html>
<html>
<head>
	<title>PHP file upload full code and script.PHP file upload examples.DEMO </title>
	<meta charset="utf-8">
	<meta name="description" content="PHP file upload full code and script.PHP file upload examples and codes ready to download and use."/>
</head>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
 choose file :<input type="file" name="file" value="Choose file">
 <input type="submit" name="upload" value="upload file">
</form>

</body>
</html>

Step 3: MySql Database

For PHP file upload script you do need to use MySQL database but I am using it to store image’s path, name, and size inside database so that I can easily create a  Dynamic gallery from it. I use a database with name test and table with name gallery. I have exported my empty gallery table so that you can easily create a table by just running below given SQL code into your MySql console or import it to your database.

gallery.sql

-- phpMyAdmin SQL Dump
-- version 4.6.6deb1+deb.cihar.com~trusty.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: May 21, 2017 at 05:30 PM
-- Server version: 5.5.55-0ubuntu0.14.04.1
-- PHP Version: 7.1.5-1+deb.sury.org~trusty+1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `gallery`
--

CREATE TABLE `gallery` (
  `id` int(10) NOT NULL,
  `path` varchar(250) NOT NULL,
  `size` varchar(250) NOT NULL,
  `name` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `gallery`
--
ALTER TABLE `gallery`
  ADD UNIQUE KEY `id` (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `gallery`
--
ALTER TABLE `gallery`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step 4: PHP upload script

Upload.php  handles the files uploaded by the user. First, it checks the is an original image or false image created by just changing the extension.Then look into uploads directory to find that file exist or not?identical files are not allowed by default. Large files are not allowed.If all condition found true, then the file is moved to uploads folder and a database record is created into gallery table associated with that file.

Upload.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$checkfile = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $checkfile = 1;
    } else {
        echo "File is not an image.
";
        $checkfile = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.
";
    echo "<img src='$target_file' height='50'width='50'>
";
    echo "<b>File Location:</b> $target_file 
";
    echo "<a href='view.php?view=gallery'><b>Show all uploaded images</b></a>
";
    $checkfile = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
    echo "Sorry, your file is too large.
";
    $checkfile = 0;

}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.
";
    $checkfile = 0;
}
// Check if $checkfile is set to 0 by an error
if ($checkfile == 0) {
    echo "Sorry, your file was not uploaded.
";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file <b>". basename( $_FILES["file"]["name"]). " has been uploaded.</b>
";
        $size=$_FILES["file"]["size"];
        $name=$_FILES["file"]["name"];
        try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO gallery (path, size, name)
    VALUES ('$target_file', '$size', '$name')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created to existing database associated to images successfully
";
    echo "<a href='view.php?view=gallery'><b>Show all uploaded images</b></a>
";
    }
    catch(PDOException $e)
    {
    echo $sql . "
" . $e->getMessage();
    }

   $conn = null;
        echo "<img src='$target_file' height='50'width='50'>
";
        echo "<b>File Location:</b> $target_file 
";
    } else {
        echo "Sorry, there was an error uploading your file.
";
    }
}
?>

Step5: View.php

View.php I just used for checking that file is uploaded and stored on uploads folder and associated record into MySQL database is working. It can also be used to create a dynamic gallery.

view.php

<?php if($_REQUEST['view']=="gallery") { $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, path, size, name  FROM gallery";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
   
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $img=$row['path'];
        echo "<img src='$img' height='100' width='100'>";
    }
    
} else {
    echo "0 results";
}
$conn->close();
}
?>

This is all done! I have used PDO and MySqli extensions for experimental purpose only you can use whatever you want to use edit replace and go.
any feedback is appreciated leave a comment or submit a message at Contact Us page.