Step-through-step Personal Home Page Tutorials For Novices – Creating Your Hypertext Preprocessor Program From Scratch: Fundamental Authentication, Membership And Crud Functionalities

This is an in depth academic on lower back-quit net development in PHP. I’ll be coaching simple CRUD functionalities, authentication, and security not a membership machine. Things like, putting in place your server, developing the general public HTML Pages, creating the database and its tables, and adding users to the database.


Interested in growing your personal website? Ever puzzled how cool it is to have a website that has a log-in/log-out functionality? Want to learn how to Create, Read, Update or Delete (CRUD) statistics in a database? Have you misplaced tune to your preceding tutorials? Well, I’m going to train you the way to create one from scratch wherein in you may recognize every single details on how the code works. If you’re new to returned-give up web development, this educational is for you. I’ll explain everything in detail so you may not have to analyze some specific techniques being used. We might not be using any frameworks to keep things simple. Also, I won’t be focusing on the web sites layout given that where after the functionalities even though, it’s clean to implement the layout. What will be doing is a easy object listing whilst the users is logged in.

*Shameless plug*

You can also checkout my ASP.NET MVC five from scratch version right here.

I also have my NodeJS/Express with MongoDB model proper right here.


In this educational, we can be using some languages that will beautify our development. If you definitely don’t know any of the matters I will mention, it is ok. Just try to go with the waft. It’s simply clean to realize them due to the fact I’m no longer into the use of advanced methods for this one. Of route because this is growing a lower back-quit provider for a internet site, you need to realize at the least the very very very fundamentals of the following:

  • HTML/CSS – Off path this will never get off the list with regards to internet improvement. Why did I even bother vicinity this? LOL.
  • JavaScript – For a redirecting script. No jQuery wished for now
  • mySQL – the maximum primary language for querying. We could be the usage of this for our CRUD (Create, Read, Update, Delete) functionalities.
  • For the software program, you may be wanting the following:

  • Text Editor – Sublime Text/Notepad++ will do. This will function our coding environment.
  • XAMPP – This will be our web server. This is wherein we will be saving our internet site files and store our facts to the database.
  • Web Browser – You can use any browser for as long because it would not devour lots of your RAM.
  • Make sure to have the ones 3 established. Do now not proceed in case you aren’t done installing them. I already provided a link to make things faster.

    For our agenda in this topic:

  • Utilize CRUD statements in SQL – Create, examine, update and delete records in a database.
  • Simple authentication and safety – Logging inside and out, dealing with unauthorized customers and restricting get admission to.
  • Simple time and date manipulation – Displaying time and date postings and tracking your posts.
  • Displaying public and personal facts – Simply display statistics for logged-in users most effective and for the general public.
  • De-briefing and Summary – Final output and some notes. FAQs also are location right here.
  • Topic Contents

    Note: In case you stopped on a sure part or need to go looking fast, you could virtually resume with the aid of pressing Ctrl + f and search for the wide variety where you ultimate stopped.

  • Setting up your server
  • Creating the public HTML Pages
  • Creating the database and its tables
  • Adding users to the database
  • User log-in: Authentication
  • Setting up the home page for Logged-in users and Logging-out
  • Testing Page Security
  • Adding information to the listing – User Access Only
  • Displaying data within the home page
  • Editing Data
  • Deleting information
  • Displaying public statistics
  • De-briefing and Summary
  • Make positive you observe chronologically. Don’t continue with out engaging in the preceding component, no longer except you realize the code.

    Some Reminders Before We Start

    Note: If the photo seems uncertain/blurry, you can click on it to view it in its larger size. Also, pardon me for the use of snap shots to display the codes in preference to displaying you a raw text because it cannot layout well on my WordPress subscription but do not worry, I’ll be importing the completed product on the quit of this academic to double-test your work.

    1) Setting Up Your Server

    Now which you are all set and cross, as the fundamentals of programming is going, allow’s begin by using growing a simple shoutout of “hello international” in our server.

    First of, visit the directory wherein you set up your XAMPP (Commonly in C:\xampp). From there, visit the htdocs folder (Commonly in C:\xampp\htdocs) and create a folder named “MyFirstWebsite”.

    From that element, you’ve got now created a Local URL for your internet site. That folder might be used to deliver in all internet site documents (.html, .Hypertext Preprocessor, .css, .js, etc.). Open up your text editor and let’s get began!

    I use chic text as my textual content editor. If your using Notepad++ or any others, it is ok. It’s not truly a massive aspect but it is just a choice on which one you would love to use.

    What we can do is a primary HTML page and show “hello global” from the server the usage of a fundamental PHP syntax. We then kind the subsequent syntax:

    <html><head><title>My first PHP Website</name></head><frame><?phpecho "<p>Hello World!</p>";?></frame>


    Save the record to the “MyFirstWebSite” Folder and name it as “index.php”. (Directory as seen at the pinnacle a part of the photo.)

    Now that you have the document. Let’s now open your XAMPP manage panel. In case it doesn’t appear in your desktop, it’s miles placed for your XAMPP folder as seen within the image:

    Now that it’s there, run your Apache and mySQL by clicking the “Start” button at the movements column. You have to see a random PID(s) and the default port number. Apache is the name of our net server wherein it’s going to deal with all of the documents as well as function the verbal exchange to the web browser and MySQL is our database so one can keep all of our records.

    Open up your web browser and inside the cope with bar, type localhost. You have to see the menu of your XAMPP.

    If it’s the first time you run it, it’s going to ask what language would you opt for, just simply pick out and it’ll lead you to the menu. If you’ll noticed the listing is localhost/xampp, it’s wherein the default web page leads you even in case you type in localhost.

    If that appears, then it method that your XAMPP server is now running. Now permit’s strive jogging the internet site you just placed. Try typing localhost/MyFirstWebsite. It must be similar to the picture underneath.

    If you’ll observe that the URL is MyFirstWebsite, it’s far derived from the htdocs folder and it automatically reads documents that are named “index”(Be it index.html, index.aspx, and so forth.), which serve as the default page. Typing localhost/MyfirstWebsite/index.personal home page is just the equal. You can also create your custom call for the URL by absolutely renaming the folder but let’s just stick to MyFirstWebsite.

    Note: If you don’t have a record named index and you entered the URL, you may receive an error 404 for no longer having the file on the server. If you do have unique documents that aren’t named index.<extention>, you need to specify the unique file name. Example: localhost/MyfirstWebsite/web page.personal home page.

    2) Creating the Public HTML Pages

    Next, permit’s re-adjust our website and upload a registration link wherein our customers can check in in addition to a Log-in web page right upon getting registered. Let’s alter our domestic web page with the following code:


    <html><head><name>My first PHP Website</identify></head><body><?phpecho "<p>Hello World!</p>";?><a href="login.php"> Click right here to login<a href="register.php"> Click here to register</body>


    As you can see, we most effective added hyperlinks which might be for the Login and register. Let’s create the registration web page first.

    register.personal home page

    <html><head><name>My first PHP Website</name></head><frame><h2>Registration Page</h2><a href="index.php">Click right here to head returned<br/><br/><shape action="check in.personal home page" technique="POST">Enter Username: <enter kind="text"call="username" required="required" /> <br/>Enter password: <input type="password"call="password" required="required" /> <br/><enter kind="submit" fee="Register"/></form></frame>


    As you can see, it is just a basic form wherein the consumer can enter his/her credentials. Now for the login page:

    Hint: Just reproduction-paste the same code to make things faster.


    <html><head><identify>My first PHP Website</name></head><frame><h2>Login Page</h2><a href="index.php">Click here to head returned<br/><br/><shape motion="checklogin.php" technique="POST">Enter Username: <input kind="textual content"call="username" required="required" /> <br/>Enter password: <input type="password"name="password" required="required" /> <br/><input kind="publish" cost="Login"/></form></frame>


    Basically, it is just the same code as from the register.Hypertext Preprocessor however the modifications made were the ones underlined.

    Click right here for the entire login.personal home page code.

    Try going for walks localhost/MyFirstWebsite once more and your pages must look like this:

    index.personal home page

    sign in.php

    three) Creating the Database and Its Tables

    Now that we’ve got our basic page for the general public. Let’s proceed to the database. First, kind localhost/phpmyadmin. This will lead you to the phpmyadmin homepage:


    From there, go to the Databases tab located on top, then from the text box in the middle, kind first_db then click on on create. Just go away the Collation as is.

    You have simply effectively created your first database. Now from there, let’s create a table wherein we are able to sign in our users and display information. First, click on on first_db located at the left facet and create a desk named customers with three columns, then click on on Go.

    For the desk’s shape, ensure to have the following fields, then click on shop:

    • Format: Column Name – Type – Length – Null Property – Other Properties
    • identification – INT – N/A – Not Null – Auto Increment
    • username – varchar – 50 – Not null
    • password – varchar – 50 – Not null

    Leave the entirety by means of default if now not targeted.

    Note: You need to scroll proper for the auto_increment. I just edited the image to healthy the A_I subject.

    Next, create any other table named listing with 7 columns and for the table’s structure:

    • id – INT – N/A – Not Null – Auto Increment
    • information – textual content – Not null
    • date_posted – varchar – 30 – Not null
    • time_posted – Time – Not null
    • date_edited – varchar – 30 – Not null
    • time_edited – Time – Not null
    • public – varchar – 5 – Not null

    4) Adding Users to the Database

    Now that we have our tables. Let’s move directly to the amusing element, getting your registration page into movement. From your registration.Hypertext Preprocessor, add the subsequent under the html codes:

    check in.php

    <html><head><identify>My first PHP Website</name></head><body><h2>Registration Page</h2><a href="index.php">Click right here to move again<br/><br/><form action="checklogin.Hypertext Preprocessor" method="POST">Enter Username: <input kind="textual content"name="username" required="required" /> <br/>Enter password: <enter kind="password"call="password" required="required" /> <br/><enter type="put up" value="Register"/></form></body>


    if($_SERVER["REQUEST METHOD"] == "POST")$username = mysql_real_escape_string($_POST['username']);$password = mysql_real_escape_string($_POST['password']);echo "Username entered is: ". $username . "<br />";echo "Password entered is: ". $password;


    Here’s the explanation to the code:

    • $_SERVER[“REQUEST_METHOD”] == “POST” – checks if the form has received a POST technique when the publish button has been clicked. The POST method is created in the html from the approach=”POST”. Click here for the shape approach reference.
    • $_POST[”] – receives the name coming from a POST technique. This simply really receives the enter primarily based on the call from the shape. In our case, it’s username and password.
    • mysql_real_escape_string() – encapsulates the input right into a string to save you inputs from SQL Injections. This ensures that your strings don’t escape from useless characters. Click here to analyze extra approximately SQL Injections.

    Now attempt to visit your sign in.Hypertext Preprocessor and attempt to input anything then click on “Register.” In my case, I positioned inside the username xtian and password as 123456. It ought to display the inputs under. Here’s my pattern:

    On this element, you ought to have understood how to get input from the shape. Now to add it to the database. On your sign in.php, upload the following code:

    sign up.php

    <html><head><identify>My first PHP Website</title></head><body><h2>Registration Page</h2><a href="index.Hypertext Preprocessor">Click right here to head again<br/><br/><form action="check in.Hypertext Preprocessor" approach="post">Enter Username: <enter kind="text"call="username" required="required" /> <br/>Enter Password: <enter type="password"call="password" required="required" /> <br/><enter kind="post" price="Register"/></shape></frame>

    </html><?personal home page

    if($_SERVER["REQUEST_METHOD"] == "POST")$username = mysql_real_escape_string($_POST['username']);$password = mysql_real_escape_string($_POST['password']);$bool = real;mysql_connect("localhost", "root","") or die(mysql_error());mysql_select_db("first_db") or due("Cannot connect with database");$query = mysql_query("Select * from customers");whilst($row = mysql_fetch_array($query))$table_users == $row['username'];if($username == $table_users)$bool = false;Print '<script>alert("Username has been taken!");</script>';Print '<script>window.area.assign("register.Hypertext Preprocessor");</script>";//redirects to//check in.personal home pageif($bool) // exams if bool is actualmysql_query("INSERT INTO users (username, password) _VALUES ('$username', 'password')"); // inserts price into desk usersPrint '<script>alert("Successfully Registered!");</script>';// Prompts the userPrint '<script>"sign up.Hypertext Preprocessor");</script>'; // redirects to// sign up.Hypertext Preprocessor


    Click right here for the complete sign in.php file

    Here are the reasons to the code:

    • mysql_connect(“Server call”,”Server Username”,”Server Password”) – The syntax used to hook up with our XAMPP server. localhost or is the call of the server. The default username is root and no password for default.
    • mysql_select_db(“database call”) – Selects the database for use.
    • or die(‘Message’) – Displays the error message if the condition wasn’t met.
    • mysql_query(‘sq. query’) – does the SQL queries. Click here for some SQL query samples. The again, I’m not here to talk about approximately mySQL.
    • mysql_fetch_array(‘query’) – fetches all queries inside the desk to show or manipulate facts. It is placed in a while loop in order that it would question all rows. Take observe that simplest 1 row is queried in step with loop it really is why some time loop is vital.
    • $row[‘row call’] – the price of the column within the present day question. It is represented as an array. In our case, $row is the name of the variable for our row within the loop.

    Try the inputs which you have made earlier and see what happens. It have to set off which you have correctly registered. Try going to phpmyadmin and notice your customers desk:

    Congratulations! Now you know how to upload data into the database with information validations.

    5) User Log-in: Authentication

    Now for the login web page. Let’s create a brand new record called checklogin.php. The cause is going lower back to our login.Hypertext Preprocessor, our shape has an movement called “checklogin.Hypertext Preprocessor”, specifically <shape motion = “checklogin.Hypertext Preprocessor” method= “POST”>. If you will word at the sign up.Hypertext Preprocessor, it is also on sign up.Hypertext Preprocessor due to the fact the back-give up is completed on the equal report as properly.

    Let’s now code the checklogin.php with the following syntax:

    checklogin.personal home page

    <?phpsession_start();$username = mysql_real_escape_string($_POST['username']);$password = mysql_real_escape_string($_POST['password']);$bool = authentic;mysql_connect("localhost", "root", "") or die (mysql_error());mysql_select_db("first_db") or die ("Cannot connect with database");$question = mysql_query("Select * from customers WHERE username='$username'");$exists = mysql_num_rows($question);$table_users = "":$table_password = "";if($exists > 0)while($row = mysql_fetch_assoc($question))$table_users = $row['username'];$table_password = $row['password'];if(($username == $table_users) && ($password == $table_password))if($password == $table_password)$_SESSION['consumer'] = $username;header("vicinity: domestic.Hypertext Preprocessor");elsePrint '<script>alert("Incorrect Password!");</script>';Print '<script>"login.personal home page");</script>';elsePrint '<script>alert("Incorrect username!");</script>';Print '<script>window.location.assign("login.personal home page");</script>';


    Click right here for the entire checklogin.personal home page code

    Here’s the reason of the code. (Some are defined in advance so there is no need to reiterate):

    • session_start() – Starts the session. This is normally accomplished on authenticated pages. The purpose why we used that is due to the fact that is required for the $_SESSION[”].
    • mysql_num_rows() – This returns an integer. This counts all the rows relying at the query.
    • $_SESSION[‘call’] – Serves as the session call for the complete session. This is surprisingly much like public variables in item-oriented programming. We will be the use of this for validating whether the person is authenticated or not.

    Now attempt to check your enter with a wrong username and password. It must return the desired set off. After checking out, try inputting an appropriate values. It need to lead you to domestic.Hypertext Preprocessor.

    Note: home.Hypertext Preprocessor does not exist yet, so it will produce an blunders 404.

    6) Setting Up the Home Page for Logged-in Users and Logging-Out

    Now that have been authenticated, let now create our home web page (home.php) with this following syntax:


    <html><head><title>My first PHP Website</title></head><?phpsession_start();if($_SESSION['person'])elseheader("region: index.personal home page");$consumer = $_SESSION['consumer'];?><body><h2>Home Page</h2><p>Hello <?Hypertext Preprocessor Print "$consumer"?>!</p> <!--<a href="logout.php">Click right here to head logout</a><br/><br/><form movement="upload.Hypertext Preprocessor" approach="POST">Add more to listing: <input type="textual content" call="information" /> <br/>Public put up? <enter kind="checkbox" name="public[]" value="yes" /> <br/><input type="submit" cost="Add to listing"/></form><h2 align="middle">My list</h2><table border="1px" width="one hundred%"><tr><th>Id</th><th>Details</th><th>Edit</th><th>Delete</th></tr></table></frame>


    Here’s the rationale to the code:

    • session_start() – Basically begins the consultation. Required for $_SESSION[”].
    • header() – redirects the person.

    Try refreshing your browser and it have to appear like this:

    Now that we have our home, let’s attempt creating our logout.php and test if the consumer’s consultation is off. What we might do is if the consumer is logged-out, the person shouldn’t get right of entry to home.Hypertext Preprocessor. So here’s the easy syntax to logout.php:


    <?phpsession_start();session_destroy();header("location:index.Hypertext Preprocessor");


    The syntax is straightforward. session_destroy() without a doubt eliminates all session’s which means, the price of $_SESSION[”] may be removed and header() will genuinely redirect it to the home web page.

    7) Testing Page Security

    Now attempt refreshing domestic.personal home page and click on logout. Now attempt clicking on the returned button of your browser and see what takes place:

    As you may see, it doesn’t direct you to domestic.php because you’re logged-out. Now for the second take a look at, try manually inputting the deal with localhost/MyFirstWebsite/home.php. The identical case must additionally take place. Since have been logged-out, even a guide input of the cope with doesn’t get admission to a certified web page. What we have carried out is a easy protection mechanism in which we redirect returned unauthorized users into a public page.

    Now strive logging in again and allow’s cross back to domestic.personal home page.

    eight) Adding Data to the List – User Access Only

    In our next step, let’s create the including of objects to the listing. As you’ll notice from the form, it’s miles written as <shape motion=”upload.Hypertext Preprocessor” approach=”POST”>, which means our http publish request is going to add.personal home page and with that, we create our add.personal home page with the subsequent syntax:

    <?phpsession_start();if($_SESSION['user'])elseheader("place:index.php");$information = mysql_real_escape_string($_POST['info']);$time = strftime("%X");$date = strftime("%B %d, %Y");Print "$time - $date - $info";


    Take be aware that this ain’t our official add.php syntax but, I’m just going to demonstrate the time and date syntax and getting your input.

    Now pass lower back to your house.personal home page and try and upload an object, then click on “Add to listing”.

    This need to be the following output on upload.personal home page:

    As you could see, we’ve got our cutting-edge time, date, and your enter. Here’s the explanation to the code:

    • strftime() – receives the time primarily based on what format your placed
    • %X – contemporary device time
    • %B – current system month
    • %d – modern-day device day
    • %Y – current gadget 12 months

    Now let’s alter our add.personal home page and upload the following information into the database together with the records from the checkbox.


    <?phpsession_start();if($_SESSION['person'])elseheader("place:index.Hypertext Preprocessor");if($_SERVER['REQUEST_METHOD'] == "POST")$details = mysql_real_escape_string($_POST['information']);$time = strftime("%X");$date = strftime("%B %d, %Y");$choice = "no";mysql_connect("localhost","root","") or die(mysql_error());mysql_select_db("first_db") or die("Cannot connect to database");foreach($_POST['public'] in $each_check)if($each_check != null)$choice = "sure";mysql_query("INSERT INTO list(details, date_posted, time_posted, public) _VALUES ('$information','$date','$time','$choice')");header("place:home.php");elseheader("vicinity:domestic.personal home page");


    Click right here for the complete upload.Hypertext Preprocessor code

    Here’s a touch explanation:

    • foreach() – gets the value of the checkbox. As you’ll word, the checkbox format within the form is call=”checkbox[]”. To get information from checkbox, it needs to be instantiated as an array. Doing so might make it viable to get facts from more than one checkboxes.

    Now strive coming into a few records and click on “Add to list”. In my case, I’ll simply use end again. Let’s visit our phpmyadmin and let’s have a look at if the facts has been brought. Here’s the result of my case:


    nine) Displaying Data in the Home Page

    Now that we’ve got seen that the facts has been efficiently added, let’s now display the records in our domestic web page. Let’s alter our home.Hypertext Preprocessor and let’s add a few columns for the date:


    <html><head><title>My first PHP Website</identify></head><?phpsession_start();if($_SESSION['person'])elseheader("location: index.php");$user = $_SESSION['person'];?><frame><h2>Home Page</h2><p>Hello <?personal home page Print "$consumer"?>!</p><a href="logout.personal home page">Click here to move logout</a><br/><br/><shape action="add.php" technique="POST">Add extra to list: <enter kind="text" name="info" /> <br/>Public post? <enter type="checkbox" name="public[]" fee="yes" /> <br/><enter kind="publish" fee="Add to list"/></form><h2 align="middle">My listing</h2><desk border="1px" width="a hundred%"><tr><th>Id</th><th>Details</th><th>Post Time</th><th>Edit Time</th><th>Edit</th><th>Delete</th><th>Public Post</th></tr><?phpmysql_connect("localhose", "root","") or die(mysql_error());mysql_select_db("first_db") or die("Cannot hook up with database");$query = mysql_query("Select * from listing");even as($row = mysql_fetch_array($query))Print "<tr>";Print '<td align="middle">'. $row['identity'] . "</td>";Print '<td align="center">'. $row['info'] . "</td>";Print '<td align="middle">'. $row['date_posted'] ." - " . $row['time_posted'] . "</td>";Print '<td align="center">'. $row['date_edited'] ." - " . $row['time_edited'] ."</td>";Print '<td align="middle"><a href="edit.php">edit</a> </td>';Print '<td align="middle"><a href="delete.Hypertext Preprocessor">delete</a> </td>';Print '<td align="center">'. $row['public'] . "</td>";Print "</tr>";?></desk></body>


    The clarification to the delivered code is quite simple. It just basically shows the facts coming from the even as loop. It has been explained earlier in our instructional so I trust that by way of this factor, you ought to have understood the system of getting the records inside the question. Going back to the browser, try refreshing your house.personal home page and notice what takes place:

    It need to now show that information. From our CRUD tick list, we’ve now finished Create and Read. Next is to replace (edit) and delete statistics. If you may word we’ve got edit and delete hyperlinks displayed at the column. I’ll add another facts to the list named “tuna” to have any other instance and this time, it’s privacy to no:

    10) Editing Data

    Let’s now attempt modifying our records and to do that we can use a new capability referred to as “GET”. With our preceding methods, we have been the use of POST as our http request but this time, allow’s use GET for modifying and deleting records. To start of, let’s regulate our home.personal home page and upload a bit code to two columns.


    <html><head><title>My first PHP Website</title></head><?phpsession_start();if($_SESSION['consumer'])elseheader("vicinity: index.php");$user = $_SESSION['consumer'];?><body><h2>Home Page</h2><p>Hello <?php Print "$user"?>!</p> <!--<a href="logout.personal home page">Click right here to go logout</a><br/><br/><form motion="upload.php" method="POST">Add greater to listing: <input type="text" call="info" /> <br/>Public put up? <input kind="checkbox" name="public[]" cost="sure" /> <br/><input kind="submit" cost="Add to listing"/></form><h2 align="center">My listing</h2><desk border="1px" width="a hundred%"><tr><th>Id</th><th>Details</th><th>Post Time</th><th>Edit Time</th><th>Edit</th><th>Delete</th><th>Public Post</th></tr><?phpmysql_connect("localhost", "root","") ordie(mysql_error()):mysql_select_db("first_db") ordie("Cannot connect with databse");$question = mysql_query("Select * from listing");while($row = mysql_fetch_array($question))Print "<tr>";Print '<td align="middle">'. $row['id'] . "</td>";Print '<td align="center">'. $row['info'] . "</td>";Print '<td align="center">'. $row['date_posted'] ." - " . $row['time_posted'] . "</td>";Print '<td align="middle">'. $row['date_edited'] ." - " . $row['time_edited'] ."</td>";Print '<td align="middle"><a href="edit.php?id='.$row['identity'] .'">edit</a></td>';Print '<td align="middle"><a href="delete.Hypertext Preprocessor?identification='.$row['identification'] .'">delete</a></td>';Print '<td align="middle">'. $row['public'] . '</td>';Print "</tr>";?></table></frame>


    If you have noticed, we only introduced URL parameter for the edit and delete links specifically identity. We might be using this later to deal with thee records. The reason why we use identity is because it’s a completely unique identifier. It is possible for the character to have input the same statistics so it’s no longer recommended to use the details as a median for manipulation in a while.

    Try placing your cursor into the edit hyperlink and you will see the price of the identification on the decrease left:

    Now that we’ve got that, permit’s try developing our edit.personal home page and permit’s try and get the information from there:

    edit.personal home page

    Lines 1 – 42:

    <html><head><name>My first PHP Website</name></head><?phpsession_start();if($_SESSION['person'])elseheader("location: index.Hypertext Preprocessor");$user = $_SESSION['consumer'];?><frame><h2>Home Page</h2><p>Hello <?personal home page Print "$person"?>!</p> <!--<a href="logout.Hypertext Preprocessor">Click here to go logout</a><br/><br/><a href="domestic.personal home page">Return to home page</a><h2 align="middle">Currently Selected</h2><table border="1px" width="100%"><tr><th>Id</th><th>Details</th><th>Post Time</th><th>Edit Time</th><th>Public Post</th></tr><?phpif(!empty($def['identification']))$identity = $_GET['identification'];$_SESSION['id'] = $id;$id_exists = proper;mysql_connect("localhost", "root","")or die(mysql_error()):mysql_select_db("first_db")or die("Cannot hook up with databse");$question = mysql_query("Select * from list");$depend = mysql_num_rows($query);if($be counted > 0)whilst($row = mysql_fetch_array($query))

    Some motives to the code:

    • !empty() – a way that checks if the price isn’t always empty. The syntax can be reversed if you need to test if it is empty via getting rid of the rationale factor (!), therefore it is syntax could be empty().
    • $_GET[”] – Used to get the price from the parameter. In our case, we use identity as our URL parameter so the syntax might be $_GET[‘id’].
    • $id_exists – the variable that tests whether or not the given id exists.
    • $_SESSION[‘identity’] – we location the fee of id into consultation to use it on any other record.

    Lines forty two – 76

    $question = mysql_query("Select * from list");$remember = mysql_num_rows($question);if($count number > zero)even as($row = mysql_fetch_array($question))Print "<tr>";Print '<td align="middle">' . $row['id'] . "</td>";Print '<td align="middle">' . $row['information'] . "</td>";Print '<td align="middle">' . $row['date_posted'] ." - " . $row['time_posted']."</td>";Print '<td align="center">' . $row['date_edited'] ." - " . $row['time_edited']."</td>";Print '<td align="middle">' . $row['public'] . "</td>";Print "</tr>";else$id_exists = false;?></table><br/><?phpif($id_exists)Print '<shape motion="edit.php" approach="submit">Enter new detail: <enter type="textual content" name="info"/><br/>public publish? <enter type="checkbox name="public[]" value="yes"/><br/><enter kind="publish" cost="Update List"/></form>';elsePrint '<h2 align="center">There isn't records to be edited.</h2>';?></body>


    The purpose why we’re putting the variable $id_exists is due to the fact in case the user modifies the URL parameter into a non-existing number (in our case we only have 2 rows/identification’s), we will display a activate wherein the facts doesn’t exist.

    Now strive clicking the edit hyperlink into the primary row and it have to show like this:

    Let’s strive modifying the URL parameter by means of putting off ?id=1 and now should result to localhost/MyFirstWebsite/edit.php and it need to result like this:

    Now try putting a price this is more than the identification wide variety, in our case, let’s try five and it ought to end result like this:


    Now that we secured our URL parameters, allow’s now area the edit syntax. Let’s go again to edit.Hypertext Preprocessor and upload some following code to update the information to the database:

    edit.Hypertext Preprocessor

    <?phpif($_SERVER['REQUEST_METHOD'] == "POST")mysql_connect("localhost", "root", "") or die (mysql_error());mysql_select_db("first_db") or die ("Cannot hook up with database");$details = mysql_real_escape_string($_POST['information']);$public = "no";$identity = $_SESSION['id'];$time = strftime("%X");$date = strftime("%B %D, %Y");foreach($_POST['public'] as $listing)if($listing != null)$public = "yes";mysql_query("UPDATE listing SET information='$information',public='$public', date_edited='$date', time_edited='$time' WHERE id='$identity'");header("place:home.Hypertext Preprocessor");


    Click here for the whole edit.personal home page code (Github).

    Now strive fresh and go returned to the edit page. Let’s attempt a extraordinary statistics. In my case, I’ll be the use of “Salmon” and exchange it to non-public:


    Go beforehand and click on Update list and you must be redirected to domestic.personal home page and notice the up to date listing.

    Now, we’ve a time and date of edit displayed at the Edit Time column. Our privateness has been set now to private and the cost has changed into Salmon.

    Congratulations! We have now accomplished the edit characteristic!

    eleven) Deleting Data

    Looking lower back to the CRUD, we’ve got now carried out developing (adding), studying (showing), and updating (editing) facts. Now for the remaining element, deleting facts. For this element, it is simply distinctly similar to what we have carried out on edit but what differs is simply the SQL statement. Instead of using UPDATE, we will be using the DELETE syntax. In deleting information, we must spark off human beings ensuring that they had really want to delete the report so we will be adding a touch JavaScript in domestic.personal home page. To try this, allow’s adjust our code and upload some in home.Hypertext Preprocessor.


    <script>function myFunction(identification)var r = affirm("Are you sure you need to delete this file?");if(r == true)window.vicinity.assign("delete.php?identification=" + id);


    Click right here for the whole home.php code

    As you have got noticed, we edited the hyperlink for the delete. We changed href into “#” and brought and onclick feature for JavaScript for the technique of myFunction and inside its parameter is the identification of the row. Below the table written is the JavaScript syntax wherein it activates the consumer if he/she desires to delete the record. If the person confirms, the page then directs to delete.Hypertext Preprocessor collectively embedded with the cost of the identity. Now allow’s create delete.personal home page and right here’s the following syntax.

    delete.Hypertext Preprocessor

    <?phpsession_start();if($_SESSION['person'])else header("area:index.php");if($_SERVER['REQUEST_METHOD'] == "GET")mysql_connect("localhost", "root", "") or die(mysql_error());mysql_select_db("first_db") or die("cannot connect to database");$id = $_GET['id'];mysql_query("DELETE FROM listing WHERE id='$id'");header("area:domestic.Hypertext Preprocessor");


    Click right here for the complete delete.php code.

    The code is simply easy and the syntax also are the ones that we used earlier than but observed we’ve got modified our request approach into GET. We are now the usage of the GET request considering we’ve a URL parameter. Now try fresh domestic.php and allow’s try deleting the primary report. This ought to be the end result:


    End-end result

    Congratulations! Now we’ve now formally completed our CRUD statements!

    12) Displaying Public Data

    Now for the final component, displaying public information. We might be displaying records that’s been set to yes in our index.Hypertext Preprocessor, wherein is a page for non-authenticated customers. It’s very simple. We simply ought to edit our index.Hypertext Preprocessor and upload a some php code and table. Here’s our updated index.personal home page:


    Now log-out and spot your default page. It have to appearance something like this:

    Note: You might not see the statistics but for the reason that we haven’t set any statistics to public.

    Now let’s log-in again and this time, permit’s add a few more data. In my case, I’ve added the following:

    • Salad – public
    • Corn – private
    • Pasta – public
    • Chicken – public
    • Spaghetti – personal

    With a total of 6 information with three of each privacy putting:


    Now allow’s log-out and notice our default web page (index.php). It have to now appear to be this:

    index.personal home page

    As you could see, it most effective display’s records which are set to public.

    Congratulations! We have subsequently finished the tutorials for this consultation!

    13) De-briefing and Summary

    In the stop, you ought to have the subsequent documents:

    As I noted earlier, I’ll be uploading the finished product. Click here.

    I also uploaded the SQL report for the database if you want to use the precise data that I have. To import the SQL record, you can just in reality click on export and choose the SQL report however ensure to create the database first. If you like, I can create a separate weblog for that. Just let me recognise within the remarks phase.

    Anticipated Questions

    Here are the questions that I think you’ll be asking. I tried to expect these to keep away from confusions:

    • Whenever I sign up a new person, the same listing appear. I was expecting for every different person, there might be a separate listing for them. Did I do some thing wrong?

    That’s certainly a great query. As you may see, I’m handiest teaching BASIC CRUD functionalities, authentication, and security now not a membership gadget. Creating a separate list in step with consumer requires a separate table for every of them. So the good judgment at the back of it’s far for each time once you insert statistics, you will insert it in any other table and feature it relationships to each other. You can use the CREATE syntax for developing a separate desk for the consumer which is going some thing like this:

    Create table $username (column1 int auto_increment, column2 varchar(50), etc...)

    You can click on here for the Create table syntax.

    The motive why I did not try this element is due to the fact you are going to have to do a variety of querying and it might make my code appearance complicating that may consume a lot of time developing it so it’s surely out of my scope. It could be higher in case you just try it out your self and discern out the way. After all, the whole lot you want is already in this blog.

    • Would it be less complicated to apply grasp pages? Because I’ve observed you needed to re-write the server and database connection all once more for every web page

    Yes, it’s far less difficult to apply master pages. The motive why I didn’t use it is for our readers to without problems understand the good judgment at the back of it. Master pages can make it a piece perplexing for starters.

    • Why now not use a framework? I wager that could appearance neat and easy.

    Then again, I noted in the identify Creating your First PHP Program FROM SCRATCH. It’s pleasant to start of from nothing that from a “template” so that our reader could realize the code with the aid of heart.

    • I recognize that this is is probably an vintage way of growing PHP. I’ve heard that there are new features released.

    I handiest offered based totally on my mastery. I’ve been running with PHP for a long time now and I might not heard about the brand new features. If you watched the new one makes it look correct, then try it out then.

    • Why now not create a separate document for the CSS and JavaScript?

    Simple, I’m most effective demonstrating you approximately the functionalities. Were more at the again-quit code in place of the the front-cease. I certainly did not targeted on the design. If you ask the way to layout your code with the PHP, nicely it’s as clean as styling a ordinary HTML report.

    Well, I wager that concludes the whole lot. Thanks men! I desire you found out some thing from this topic.

    Just to reiterate, if you need to learn making your own ASP.NET MVC 5 net software from scratch, you can take a look at it out proper here. Follow me on Twitter and you could tweet out your feedbacks and comments on either articles.

    Related Posts

    Leave a Reply

    Your email address will not be published. Required fields are marked *