Sunday, July 31, 2016

How to Create a PHP/MySQL Powered Forum from Scratch_part2

Step 4: Displaying the Forum Overview

Since we're just started with some basic techniques, we're going to make a simplified version of the forum overview for now.
  1. <?php
  2. //create_cat.php
  3. include 'connect.php';
  4. include 'header.php';
  5.          
  6. echo '<tr>';
  7.     echo '<td class="leftpart">';
  8.         echo '<h3><a href="category.php?id=">
  9. Category name</a></h3>
  10.  Category description goes here';
  11.     echo '</td>';
  12.     echo '<td class="rightpart">';                
  13.             echo '<a href="topic.php?id=">
  14. Topic subject</a> at 10-10';
  15.     echo '</td>';
  16. echo '</tr>';
  17. include 'footer.php';
  18. ?>
There you have it: a nice and clean overview. We'll be updating this page throughout the tutorial so that it becomes more like the end result, step by step!

Step 5: Signing up a User

Let's start by making a simple HTML form so that a new user can register.


A PHP page is needed to process the form. We're going to use a $_SERVER variable. The $_SERVER variable is an array with values that are automatically set with each request. One of the values of the $_SERVER array is 'REQUEST_METHOD'. When a page is requested with GET, this variable will hold the value 'GET'. When a page is requested via POST, it will hold the value 'POST'. We can use this value to check if a form has been posted. See the signup.php page below.
  1. <?php
  2. //signup.php
  3. include 'connect.php';
  4. include 'header.php';
  5.  
  6. echo '<h3>Sign up</h3>';
  7.  
  8. if($_SERVER['REQUEST_METHOD'] != 'POST')
  9. {
  10.     /*the form hasn't been posted yet, display it
  11.       note that the action="" will cause the form to post to the same page it is on */
  12.     echo '<form method="post" action="">
  13.         Username: <input type="text" name="user_name" />
  14.         Password: <input type="password" name="user_pass">
  15.         Password again: <input type="password" name="user_pass_check">
  16.         E-mail: <input type="email" name="user_email">
  17.         <input type="submit" value="Add category" />
  18.      </form>';
  19. }
  20. else
  21. {
  22.     /* so, the form has been posted, we'll process the data in three steps:
  23.         1.  Check the data
  24.         2.  Let the user refill the wrong fields (if necessary)
  25.         3.  Save the data 
  26.     */
  27.     $errors = array(); /* declare the array for later use */
  28.      
  29.     if(isset($_POST['user_name']))
  30.     {
  31.         //the user name exists
  32.         if(!ctype_alnum($_POST['user_name']))
  33.         {
  34.             $errors[] = 'The username can only contain letters and digits.';
  35.         }
  36.         if(strlen($_POST['user_name']) > 30)
  37.         {
  38.             $errors[] = 'The username cannot be longer than 30 characters.';
  39.         }
  40.     }
  41.     else
  42.     {
  43.         $errors[] = 'The username field must not be empty.';
  44.     }
  45.      
  46.      
  47.     if(isset($_POST['user_pass']))
  48.     {
  49.         if($_POST['user_pass'] != $_POST['user_pass_check'])
  50.         {
  51.             $errors[] = 'The two passwords did not match.';
  52.         }
  53.     }
  54.     else
  55.     {
  56.         $errors[] = 'The password field cannot be empty.';
  57.     }
  58.      
  59.     if(!empty($errors)) /*check for an empty array, if there are errors,
  60.  they're in this array (note the ! operator)*/
  61.     {
  62.         echo 'Uh-oh.. a couple of fields are not filled in correctly..';
  63.         echo '<ul>';
  64.         foreach($errors as $key => $value)
  65.  /* walk through the array so all the errors get displayed */
  66.         {
  67.             echo '<li>' . $value . '</li>';
  68.  /* this generates a nice error list */
  69.         }
  70.         echo '</ul>';
  71.     }
  72.     else
  73.     {
  74.         //the form has been posted without, so save it
  75.         //notice the use of mysql_real_escape_string, keep everything safe!
  76.         //also notice the sha1 function which hashes the password
  77.         $sql = "INSERT INTO
  78.                     users(user_name, user_pass, user_email ,user_date, user_level)
  79.                 VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
  80.                        '" . sha1($_POST['user_pass']) . "',
  81.                        '" . mysql_real_escape_string($_POST['user_email']) . "',
  82.                         NOW(),
  83.                         0)";
  84.                          
  85.         $result = mysql_query($sql);
  86.         if(!$result)
  87.         {
  88.             //something went wrong, display the error
  89.             echo 'Something went wrong while registering. 
  90. Please try again later.';
  91.             //echo mysql_error(); //debugging purposes,
  92.  uncomment when needed
  93.         }
  94.         else
  95.         {
  96.             echo 'Successfully registered. 
  97. You can now <a href="signin.php">sign in</a> and start posting! :-)';
  98.         }
  99.     }
  100. }
  101.  
  102. include 'footer.php';
  103. ?>
A lot of explanation is in the comments I made in the file, so be sure to check them out. The processing of the data takes place in three parts:
  • Validating the data
  • If the data is not valid, show the form again
  • If the data is valid, save the record in the database
The PHP part is quite self-explanatory. The SQL-query however probably needs a little more explanation.
  1. INSERT INTO
  2.        users(user_name, user_pass, user_email ,user_date, user_level)
  3. VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
  4.        '" . sha1($_POST['user_pass']) . "',
  5.        '" . mysql_real_escape_string($_POST['user_email']) . "',
  6.        NOW(),   
  7.        0);
On line 1 we have the INSERT INTO statement which speaks for itself. The table name is specified on the second line. The words between the brackets represent the columns in which we want to insert the data. The VALUES statement tells the database we're done declaring column names and it's time to specify the values. There is something new here: mysql_real_escape_string. The function escapes special characters in an unescaped string , so that it is safe to place it in a query. This function MUST always be used, with very few exceptions. There are too many scripts that don't use it and can be hacked real easy. Don't take the risk, use mysql_real_escape_string().
"Never insert a plain password as-is. You MUST always encrypt it."
Also, you can see that the function sha1() is used to encrypt the user's password. This is also a very important thing to remember. Never insert a plain password as-is. You MUST always encrypt it. Imagine a hacker who somehow manages to get access to your database. If he sees all the plain-text passwords he could log into any (admin) account he wants. If the password columns contain sha1 strings he has to crack them first which is almost impossible.

Note: it's also possible to use md5(), I always use sha1() because benchmarks have proved it's a tiny bit faster, not much though. You can replace sha1 with md5 if you like.

If the signup process was successful, you should see something like this:


Try refreshing your phpMyAdmin screen, a new record should be visible in the users table.

Step 6: Adding Authentication and User Levels

An important aspect of a forum is the difference between regular users and admins/moderators. Since this is a small forum and adding features like adding new moderators and stuff would take way too much time, we'll focus on the login process and create some admin features like creating new categories and closing a thread.

Now that you've completed the previous step, we're going to make your freshly created account an admin account. In phpMyAdmin, click on the users table, and then 'Browse'. Your account will probably pop up right away. Click the edit icon and change the value of the user_level field from 0 to 1. That's it for now. You won't notice any difference in our application immediately, but when we've added the admin features a normal account and your account will have different capabilities.

The sign-in process works the following way:
  • A visitor enters user data and submits the form
  • If the username and password are correct, we can start a session
  • If the username and password are incorrect, we show the form again with a message
https://school.codequs.com/p/rJqQzyIO

The signin.php file is below. Don't think I'm not explaining what I'm doing, but check out the comments in the file. It's much easier to understand that way.
  1. <?php
  2. //signin.php
  3. include 'connect.php';
  4. include 'header.php';
  5. echo '<h3>Sign in</h3>';
  6. //first, check if the user is already signed in. If that is the case,
  7. there is no need to display this page
  8. if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
  9. {
  10. echo 'You are already signed in,
  11. you can <a href="signout.php">sign out</a> if you want.';
  12. }
  13. else
  14. {
  15. if($_SERVER['REQUEST_METHOD'] != 'POST')
  16. {
  17. /*the form hasn't been posted yet, display it
  18. note that the action="" will cause the form to post to the same page it is on */
  19. echo '<form method="post" action="">
  20. Username: <input type="text" name="user_name" />
  21. Password: <input type="password" name="user_pass">
  22. <input type="submit" value="Sign in" />
  23. </form>';
  24. }
  25. else
  26. {
  27. /* so, the form has been posted, we'll process the data in three steps:
  28. 1. Check the data
  29. 2. Let the user refill the wrong fields (if necessary)
  30. 3. Varify if the data is correct and return the correct response
  31. */
  32. $errors = array(); /* declare the array for later use */
  33. if(!isset($_POST['user_name']))
  34. {
  35. $errors[] = 'The username field must not be empty.';
  36. }
  37. if(!isset($_POST['user_pass']))
  38. {
  39. $errors[] = 'The password field must not be empty.';
  40. }
  41. if(!empty($errors)) /*check for an empty array, if there are errors,
  42. they're in this array (note the ! operator)*/
  43. {
  44. echo 'Uh-oh.. a couple of fields are not filled in correctly..';
  45. echo '<ul>';
  46. foreach($errors as $key => $value)
  47. /* walk through the array so all the errors get displayed */
  48. {
  49. echo '<li>' . $value . '</li>'; /* this generates a nice error list */
  50. }
  51. echo '</ul>';
  52. }
  53. else
  54. {
  55. //the form has been posted without errors, so save it
  56. //notice the use of mysql_real_escape_string, keep everything safe!
  57. //also notice the sha1 function which hashes the password
  58. $sql = "SELECT
  59. user_id,
  60. user_name,
  61. user_level
  62. FROM
  63. users
  64. WHERE
  65. user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
  66. AND
  67. user_pass = '" . sha1($_POST['user_pass']) . "'";
  68. $result = mysql_query($sql);
  69. if(!$result)
  70. {
  71. //something went wrong, display the error
  72. echo 'Something went wrong while signing in. Please try again later.';
  73. //echo mysql_error(); //debugging purposes, uncomment when needed
  74. }
  75. else
  76. {
  77. //the query was successfully executed, there are 2 possibilities
  78. //1. the query returned data, the user can be signed in
  79. //2. the query returned an empty result set, the credentials were wrong
  80. if(mysql_num_rows($result) == 0)
  81. {
  82. echo 'You have supplied a wrong user/password combination. Please try again.';
  83. }
  84. else
  85. {
  86. //set the $_SESSION['signed_in'] variable to TRUE
  87. $_SESSION['signed_in'] = true;
  88. //we also put the user_id and user_name values in the $_SESSION,
  89. so we can use it at various pages
  90. while($row = mysql_fetch_assoc($result))
  91. {
  92. $_SESSION['user_id'] = $row['user_id'];
  93. $_SESSION['user_name'] = $row['user_name'];
  94. $_SESSION['user_level'] = $row['user_level'];
  95. }
  96. echo 'Welcome, ' . $_SESSION['user_name'] . '.
  97. <a href="index.php">Proceed to the forum overview</a>.';
  98. }
  99. }
  100. }
  101. }
  102. }
  103. include 'footer.php';
  104. ?>
This is the query that's in the signin.php file:
  1. SELECT
  2.     user_id,
  3.     user_name,
  4.     user_level
  5. FROM
  6.     users
  7. WHERE
  8.     user_name = '" .
  9.  mysql_real_escape_string($_POST['user_name']) . "'
  10. AND
  11.     user_pass = '" . sha1($_POST['user_pass'])
It's obvious we need a check to tell if the supplied credentials belong to an existing user. A lot of scripts retrieve the password from the database and compare it using PHP. If we do this directly via SQL the password will be stored in the database once during registration and never leave it again. This is safer, because all the real action happens in the database layer and not in our application.

If the user is signed in successfully, we're doing a few things:
  1. <?php
  2. //set the $_SESSION['signed_in'] variable to TRUE
  3. $_SESSION['signed_in'] = true;                  
  4. //we also put the user_id and user_name 
  5. values in the $_SESSION, so we can use it at various pages
  6. while($row = mysql_fetch_assoc($result))
  7. {
  8.     $_SESSION['user_id'] = $row['user_id'];
  9.     $_SESSION['user_name'] = $row['user_name']; 
  10. }
  11. ?>
First, we set the 'signed_in' $_SESSION var to true, so we can use it on other pages to make sure the user is signed in. We also put the username and user id in the $_SESSION variable for usage on a different page. Finally, we display a link to the forum overview so the user can get started right away.

Of course signing in requires another function, signing out! The sign-out process is actually a lot easier than the sign-in process. Because all the information about the user is stored in $_SESSION variables, all we have to do is unset them and display a message.

Now that we've set the $_SESSION variables, we can determine if someone is signed in. Let's make a last simple change to header.php:

Replace:
  1. <div id="userbar">Hello Example. Not you? Log out.</div>
With:
  1. <?php
  2. <div id="userbar">
  3.     if($_SESSION['signed_in'])
  4.     {
  5.         echo 'Hello' . $_SESSION['user_name'] . '.
  6.  Not you? <a href="signout.php">Sign out</a>';
  7.     }
  8.     else
  9.     {
  10.         echo '<a href="signin.php">Sign in</a> or
  11.  <a href="sign up">create an account</a>.';
  12.     }
  13. </div>
If a user is signed in, he will see his or her name displayed on the front page with a link to the signout page. Our authentication is done! By now our forum should look like this:

https://school.codequs.com/p/rJqQzyIO

Step 7: Creating a Category

We want to create categories so let's start with making a form.

  1. <form method="post" action="">
  2.     Category name: <input type="text" name="cat_name" />
  3.     Category description: <textarea name="cat_description" /></textarea>
  4.     <input type="submit" value="Add category" />
  5.  </form>
This step looks a lot like Step 4 (Signing up a user'), so I'm not going to do an in-depth explanation here. If you followed all the steps you should be able to understand this somewhat quickly.

  1. <?php
  2. //create_cat.php
  3. include 'connect.php';
  4.  
  5. if($_SERVER['REQUEST_METHOD'] != 'POST')
  6. {
  7.     //the form hasn't been posted yet, display it
  8.     echo '<form method='post' action=''>
  9.         Category name: <input type='text' name='cat_name' />
  10.         Category description: <textarea name='cat_description' /></textarea>
  11.         <input type='submit' value='Add category' />
  12.      </form>';
  13. }
  14. else
  15. {
  16.     //the form has been posted, so save it
  17.     $sql = ìINSERT INTO categories(cat_name, cat_description)
  18.        VALUES('' . mysql_real_escape_string($_POST['cat_name']) . ì',
  19.              '' . mysql_real_escape_string($_POST['cat_description']) . ì')';
  20.     $result = mysql_query($sql);
  21.     if(!$result)
  22.     {
  23.         //something went wrong, display the error
  24.         echo 'Error' . mysql_error();
  25.     }
  26.     else
  27.     {
  28.         echo 'New category successfully added.';
  29.     }
  30. }
  31. ?>

As you can see, we've started the script with the $_SERVER check, after checking if the user has admin rights, which is required for creating a category. The form gets displayed if it hasn't been submitted already. If it has, the values are saved. Once again, a SQL query is prepared and then executed.

https://school.codequs.com/p/rJqQzyIO
                                                Source: tutsplus (countinue )
If you feel useful for you and for everyone, please share it!
Suggest for you:

Learning PHP 7: From the Basics to Application Development

The Complete PHP 7 Guide for Web Developers

Up to Speed with PHP 7

Learn PHP 7 This Way to Rise Above & Beyond Competion!

The Complete PHP with MySQL Developer Course (New)

Saturday, July 30, 2016

How to Create a PHP/MySQL Powered Forum from Scratch_part1

In this tutorial, we're going to build a PHP/MySQL powered forum from scratch. This tutorial is perfect for getting used to basic PHP and database usage. Let's dive right in!

Step 1: Creating Database Tables

It's always a good idea to start with creating a good data model when building an application. Let's describe our application in one sentence: We are going to make a forum which has users who create topics in various categories. Other users can post replies. As you can see, I highlighted a couple of nouns which represent our table names.

Users
  • Categories
  • Topics
  • Posts
These three objects are related to each other, so we'll process that in our table design. Take a look at the scheme below.

https://school.codequs.com/p/rJqQzyIO
Looks pretty neat, huh? Every square is a database table. All the columns are listed in it and the lines between them represent the relationships. I'll explain them further, so it's okay if it doesn't make a lot of sense to you right now.

I'll discuss each table by explaining the SQL, which I created using the scheme above. For your own scripts you can create a similar scheme and SQL too. Some editors like MySQL Workbench (the one I used) can generate .sql files too, but I would recommend learning SQL because it's more fun to do it yourself. A SQL introduction can be found at W3Schools.

Users Table
  1. CREATE TABLE users (
  2. user_id     INT(8) NOT NULL AUTO_INCREMENT,
  3. user_name   VARCHAR(30) NOT NULL,
  4. user_pass   VARCHAR(255) NOT NULL,
  5. user_email  VARCHAR(255) NOT NULL,
  6. user_date   DATETIME NOT NULL,
  7. user_level  INT(8) NOT NULL,
  8. UNIQUE INDEX user_name_unique (user_name),
  9. PRIMARY KEY (user_id)
  10. ) TYPE=INNODB;
The CREATE TABLE statement is used to indicate we want to create a new table, of course. The statement is followed by the name of the table and all the columns are listed between the brackets. The names of all the fields are self-explanatory, so we'll only discuss the data types below.

user_id
"A primary key is used to uniquely identify each row in a table."
The type of this field is INT, which means this field holds an integer. The field cannot be empty (NOT NULL) and increments which each record inserted. At the bottom of the table you can see the user_id field is declared as a primary key. A primary key is used to uniquely identify each row in a table. No two distinct rows in a table can have the same value (or combination of values) in all columns. That might be a bit unclear, so here's a little example.

There is a user called John Doe. If another users registers with the same name, there's a problem, because: which user is which? You can't tell and the database can't tell either. By using a primary key this problem is solved, because both topics are unique.

All the other tables have got primary keys too and they work the same way.

user_name

This is a text field, called a VARCHAR field in MySQL. The number between brackets is the maximum length. A user can choose a username up to 30 characters long. This field cannot be NULL. At the bottom of the table you can see this field is declared UNIQUE, which means the same username cannot be registered twice. The UNIQUE INDEX part tells the database we want to add a unique key. Then we define the name of the unique key, user_name_unique in this case. Between brackets is the field the unique key applies to, which is user_name.

user_pass

This field is equal to the user_name field, except the maximum length. Since the user password, no matter what length, is hashed with sha1(), the password will always be 40 characters long.

user_email

This field is equal to the user_pass field.

user_date

This is a field in which we'll store the date the user registered. It's type is DATETIME and the field cannot be NULL.

user_level

This field contains the level of the user, for example: '0' for a regular user and '1' for an admin. More about this later.

Categories Table 
  1. CREATE TABLE categories (
  2. cat_id          INT(8) NOT NULL AUTO_INCREMENT,
  3. cat_name        VARCHAR(255) NOT NULL,
  4. cat_description     VARCHAR(255) NOT NULL,
  5. UNIQUE INDEX cat_name_unique (cat_name),
  6. PRIMARY KEY (cat_id)
  7. ) TYPE=INNODB;
 These data types basically work the same way as the ones in the users table. This table also has a primary key and the name of the category must be an unique one.

Topics Table
  1. CREATE TABLE topics (
  2. topic_id        INT(8) NOT NULL AUTO_INCREMENT,
  3. topic_subject       VARCHAR(255) NOT NULL,
  4. topic_date      DATETIME NOT NULL,
  5. topic_cat       INT(8) NOT NULL,
  6. topic_by        INT(8) NOT NULL,
  7. PRIMARY KEY (topic_id)
  8. ) TYPE=INNODB;
This table is almost the same as the other tables, except for the topic_by field. That field refers to the user who created the topic. The topic_cat refers to the category the topic belongs to. We cannot force these relationships by just declaring the field. We have to let the database know this field must contain an existing user_id from the users table, or a valid cat_id from the categories table. We'll add some relationships after I've discussed the posts table.

Posts Table
  1. CREATE TABLE posts (
  2. post_id         INT(8) NOT NULL AUTO_INCREMENT,
  3. post_content        TEXT NOT NULL,
  4. post_date       DATETIME NOT NULL,
  5. post_topic      INT(8) NOT NULL,
  6. post_by     INT(8) NOT NULL,
  7. PRIMARY KEY (post_id)
  8. ) TYPE=INNODB;
This is the same as the rest of the tables; there's also a field which refers to a user_id here: the post_by field. The post_topic field refers to the topic the post belongs to.
"A foreign key is a referential constraint between two tables. The foreign key identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table."
Now that we've executed these queries, we have a pretty decent data model, but the relations are still missing. Let's start with the definition of a relationship. We're going to use something called a foreign key. A foreign key is a referential constraint between two tables. The foreign key identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table. Some conditions:
  • The column in the referencing table the foreign key refers to must be a primary key
  • The values that are referred to must exist in the referenced table
By adding foreign keys the information is linked together which is very important for database normalization. Now you know what a foreign key is and why we're using them. It's time to add them to the tables we've already made by using the ALTER statement, which can be used to change an already existing table.

We'll link the topics to the categories first:
  1. ALTER TABLE topics ADD FOREIGN KEY(topic_cat) REFERENCES categories(cat_id)
  2.  ON DELETE CASCADE ON UPDATE CASCADE;
The last part of the query already says what happens. When a category gets deleted from the database, all the topics will be deleted too. If the cat_id of a category changes, every topic will be updated too. That's what the ON UPDATE CASCADE part is for. Of course, you can reverse this to protect your data, so that you can't delete a category as long as it still has topics linked to it. If you would want to do that, you could replace the 'ON DELETE CASCADE' part with 'ON DELETE RESTRICT'. There is also SET NULL and NO ACTION, which speak for themselves.

Every topic is linked to a category now. Let's link the topics to the user who creates one.
  1. ALTER TABLE topics ADD FOREIGN KEY(topic_by) REFERENCES users(user_id)
  2.  ON DELETE RESTRICT ON UPDATE CASCADE;
This foreign key is the same as the previous one, but there is one difference: the user can't be deleted as long as there are still topics with the user id of the user. We don't use CASCADE here because there might be valuable information in our topics. We wouldn't want that information to get deleted if someone decides to delete their account. To still give users the opportunity to delete their account, you could build some feature that anonymizes all their topics and then delete their account. Unfortunately, that is beyond the scope of this tutorial.

Link the posts to the topics:
  1. ALTER TABLE posts ADD FOREIGN KEY(post_topic) REFERENCES topics(topic_id) ON DELETE CASCADE ON UPDATE CASCADE;
And finally, link each post to the user who made it:
  1. ALTER TABLE posts ADD FOREIGN KEY(post_by) REFERENCES users(user_id) ON DELETE RESTRICT ON UPDATE CASCADE;
That's the database part! It was quite a lot of work, but the result, a great data model, is definitely worth it.

Step 2: Introduction to the Header/Footer System

Each page of our forum needs a few basic things, like a doctype and some markup. That's why we'll include a header.php file at the top of each page, and a footer.php at the bottom. The header.php contains a doctype, a link to the stylesheet and some important information about the forum, such as the title tag and metatags.

header.php
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" lang="nl">

  4. <head>

  5.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

  6.     <meta name="description" content="A short description." />

  7.     <meta name="keywords" content="put, keywords, here" />

  8.     <title>PHP-MySQL forum</title>

  9.     <link rel="stylesheet" href="style.css" type="text/css">

  10. </head>

  11. <body>

  12. <h1>My forum</h1>

  13.     <div id="wrapper">

  14.     <div id="menu">

  15.         <a class="item" href="/forum/index.php">Home</a> -

  16.         <a class="item" href="/forum/create_topic.php">Create a topic</a> -

  17.         <a class="item" href="/forum/create_cat.php">Create a category</a>

  18.          

  19.         <div id="userbar">

  20.         <div id="userbar">Hello Example. Not you? Log out.</div>

  21.     </div>

  22.         <div id="content">
The wrapper div will be used to make it easier to style the entire page. The menu div obviously contains a menu with links to pages we still have to create, but it helps to see where we're going a little bit. The userbar div is going to be used for a small top bar which contains some information like the username and a link to the logout page. The content page holds the actual content of the page, obviously.

The attentive reader might have already noticed we're missing some things. There is no </body> or </html> tag. They're in the footer.php page, as you can see below.
  1. </div><!-- content -->
  2. </div><!-- wrapper -->
  3. <div id="footer">Created for Nettuts+</div>
  4. </body>
  5. </html>
When we include a header and a footer on each page the rest of the page get embedded between the header and the footer. This method has got some advantages. First and foremost, everything will be styled correctly. A short example:
  1. <?php
  2. $error = false;
  3. if($error = false)
  4. {
  5.     //the beautifully styled content, everything looks good
  6.     echo '<div id="content">some text</div>';
  7. }
  8. else
  9. {
  10.     //bad looking, unstyled error :-( 
  11. ?>
As you can see, a page without errors will result in a nice page with the content. But if there's an error, everything looks really ugly; so that's why it's better to make sure not only real content is styled correctly, but also the errors we might get.

Another advantage is the possibility of making quick changes. You can see for yourself by editing the text in footer.php when you've finished this tutorial; you'll notice that the footer changes on every page immediately. Finally, we add a stylesheet which provides us with some basic markup - nothing too fancy.
  1. body {
  2.     background-color: #4E4E4E;
  3.     text-align: center;         /* make sure IE centers the page too */
  4. }
  5. #wrapper {
  6.     width: 900px;
  7.     margin: 0 auto;             /* center the page */
  8. }
  9. #content {
  10.     background-color: #fff;
  11.     border: 1px solid #000;
  12.     float: left;
  13.     font-family: Arial;
  14.     padding: 20px 30px;
  15.     text-align: left;
  16.     width: 100%;                /* fill up the entire div */
  17. }
  18. #menu {
  19.     float: left;
  20.     border: 1px solid #000;
  21.     border-bottom: none;        /* avoid a double border */
  22.     clear: both;                /* clear:both makes sure the content div doesn't float next to this one but stays under it */
  23.     width:100%;
  24.     height:20px;
  25.     padding: 0 30px;
  26.     background-color: #FFF;
  27.     text-align: left;
  28.     font-size: 85%;
  29. }
  30. #menu a:hover {
  31.     background-color: #009FC1;
  32. }
  33. #userbar {
  34.     background-color: #fff;
  35.     float: right;
  36.     width: 250px;
  37. }
  38. #footer {
  39.     clear: both;
  40. }
  41. /* begin table styles */
  42. table {
  43.     border-collapse: collapse;
  44.     width: 100%;
  45. }
  46. table a {
  47.     color: #000;
  48. }
  49. table a:hover {
  50.     color:#373737;
  51.     text-decoration: none;
  52. }
  53. th {
  54.     background-color: #B40E1F;
  55.     color: #F0F0F0;
  56. }
  57. td {
  58.     padding: 5px;
  59. }
  60. /* Begin font styles */
  61. h1, #footer {
  62.     font-family: Arial;
  63.     color: #F1F3F1;
  64. }
  65. h3 {margin: 0; padding: 0;}
  66. /* Menu styles */
  67. .item {
  68.     background-color: #00728B;
  69.     border: 1px solid #032472;
  70.     color: #FFF;
  71.     font-family: Arial;
  72.     padding: 3px;
  73.     text-decoration: none;
  74. }
  75. .leftpart {
  76.     width: 70%;
  77. }
  78. .rightpart {
  79.     width: 30%;
  80. }
  81. .small {
  82.     font-size: 75%;
  83.     color: #373737;
  84. }
  85. #footer {
  86.     font-size: 65%;
  87.     padding: 3px 0 0 0;
  88. }
  89. .topic-post {
  90.     height: 100px;
  91.     overflow: auto;
  92. }
  93. .post-content {
  94.     padding: 30px;
  95. }
  96. textarea {
  97.     width: 500px;
  98.     height: 200px;
  99. }
Step 3: Getting Ready for Action

Before we can read anything from our database, we need a connection. That's what connect.php is for. We'll include it in every file we are going to create.
  1. <?php
  2. //connect.php
  3. $server = 'localhost';
  4. $username   = 'usernamehere';
  5. $password   = 'passwordhere';
  6. $database   = 'databasenamehere';
  7. if(!mysql_connect($server, $username,  $password))
  8. {
  9.     exit('Error: could not establish database connection');
  10. }
  11. if(!mysql_select_db($database)
  12. {
  13.     exit('Error: could not select the database');
  14. }
  15. ?>
Simply replace the default values of the variables at the top of the page with your own date, save the file and you're good to go!
Source: tutsplus (countinue )

For more information , please support and follow us.
 Suggest for you:

The Complete PHP with MySQL Developer Course (New)

PHP MySQL Database Connections

Learn Database Design with MySQL

Modern Programming with PHP

Learn Redis from Scratch

Wednesday, July 27, 2016

Java 7 New Features

This tutorial covers the new features added in java programming language as part of Java7 release.

Please note that this tutorial doesn't contain the full list of new features introduced in Java SE7. This rather concentrates on changes to Java Programming Language and doesn't go in details of changes to I/O, concurrent utilities, Security, JVM, Networking, RIA, JDBC changes. For release notes of java7, please visit here

Java Programming Language

Binary Literals:

Starting Java7, all the number types (byte, short, int, long) can be expressed using the binary number system. In order to do same, add the prefix 0b or 0B to the number as shown in following examples. This could be helpful in getting better visibility when doing the bit level operations -
ta from a table using JDBC will look like before java7 -

//byte value (8-bit) expressed in binary number system
byte numByte = (byte) 0b10010001;

//short value (16-bit) expressed in binary number system
short numShort = (short) 0b1001000100011110;

//int value (32-bit) expressed in binary number system
int numInt =  0b10010001000111101010101001010101;

//long value (64-bit) expressed in binary number system

long numLong =  0b1001000100011110101010100101010110010001000111101010101001010101L;

Strings in Switch Statements:

Finally you can use a String object in a switch statement expression. The switch statement compares the expression String with each case lable by calling String.equals method. Here is an example of that -

Java7StringsInSwitchStatement.java
package com.sts.allprogtutorials;

/**
 * @author Sain Technology Solutions
 *
 */
public class Java7StringsInSwitchStatement {

    /**
     * @param args
*/
public static void main(String[] args) {
final String programmingLanguage = "Java";

String programmingLanguageType = null;
switch(programmingLanguage) {
case "C++"  :
case "Java" : 
programmingLanguageType = "Object Oriented Programming Language";
break;
case "C" :
programmingLanguageType = "Procedural Programming Language";
}

System.out.println("Programming Language: " + programmingLanguage + " is of type: " + programmingLanguageType);
}

}

If you run the above program, you get output as 'Programming Language: Java is of type: Object Oriented Programming Language'.

The try-with-resources Statement:

Have you ever missed to close any stream/jdbc statements or you are annoyed with closing the streams to close everytime you use it? Well, there is a good news for you that developers no longer need to close the streams/statements explicitly as it is taken care by JVM automatically if you use try-with-resources.


This is how a typical code to read the data from a table using JDBC will look like before java7 -

public static void printEmployeesWithoutTryWithResource(Connection connection) {

PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

String query = "select EMP_ID, EMP_NAME, EMP_EMAIL, EMP_DOB from EMPLOYEE";
try{
preparedStatement = connection.prepareStatement(query);
resultSet = preparedStatement.executeQuery();

while(resultSet.next()) {
final Long empId = resultSet.getLong("EMP_ID");
final String empName = resultSet.getString("EMP_NAME");
final String empEmail = resultSet.getString("EMP_EMAIL");
final Date dOB = resultSet.getDate("EMP_DOB");
System.out.println("[" + empId + ", " + empName + ", " + empEmail + ", " + dOB + "]");
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
} finally {
try {
if(resultSet != null && !resultSet.isClosed()) {
resultSet.close();
}

if(preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
}catch (SQLException sqlException1) {
sqlException1.printStackTrace();
}
}

}

Here is how it will look like if you use try-with-resources statement (notice parenthesis after try) -

public static void printEmployeesUsingTryWithResource(Connection connection) {

String query = "select EMP_ID, EMP_NAME, EMP_EMAIL, EMP_DOB from EMPLOYEE";
try(
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
){
while(resultSet.next()) {
final Long empId = resultSet.getLong("EMP_ID");
final String empName = resultSet.getString("EMP_NAME");
final String empEmail = resultSet.getString("EMP_EMAIL");
final Date dOB = resultSet.getDate("EMP_DOB");
System.out.println("[" + empId + ", " + empName + ", " + empEmail + ", " + dOB + "]");
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();


}

Please note that PreparedStatement and ResultSet used above belong to JDBC 4.1 and extend AutoCloseable interface. In general, any class/interface implementing/extending AutoCloseable or Closeable (it extends AutoCloseable) interface, can be initialised (read autoclosed) in try-with-resources statement.

Above example doesn't show finally block but you can use finally just like you use it in traditional try block.

Handling More Than One Type of Exception in One Catch Block:


Java7 lets you handle more than one type of exceptions in one catch block and therefore reducing redundancy in the code. Let's have a look at following code handing 3 different type of exceptions prior to java7 -

try {
//Statements that could throw either SQLEXception or IOException
} catch(SQLException exception) {
exception.printStackTrace();
throw exception;
} catch(IOException exception) {
exception.printStackTrace();
throw exception;

}

And here is how it will look like in java7 -

try {
//Statements that could throw either SQLEXception or IOException
} catch(SQLException|IOException exception) {
exception.printStackTrace();
throw exception;

}

You can handle as many exceptions as you want in this way but one thing worth mentioning is that all of the exceptions must be siblings i.e. if you can not use any of the exception which is parent/child of any of other exceptions already specified in catch block. For instance, following will not work -

try {
//Statements that could throw either SQLEXception or IOException
} catch(SQLException|Exception exception) { //Compilation error as Exception is parent of SQLException
exception.printStackTrace();
throw exception;
}

Underscores in Numeric Literals:

Starting Java 7, numerical literals can have any number of underscore characters anywhere between the digits. But no underscores are allowed in starting or ending of literal. This can be useful when you are dealing with big numbers or non-decimal number system and wants to make it more readable. Following are some of the valid and non-valid expressions -

Valid Numeric Expressions containing Underscore characters
long hex = 0xAE_FF_FE_DE;
long creditCardNo = 4321_8765_1234_5678L;
float pi = 1_23.45_67_89F;

double amount = 1_257_434_656.34;

Non-valid Numeric Expressions containing Underscore characters
long creditCardNo1 = _4321_8765_1234_5678L; //can't put underscore in starting of number as it makes it an identifier
long creditCardNo2 = 4321_8765_1234_5678L_; //can't put underscore in the end
long creditCardNo3 = 4321_8765_1234_5678_L; //can't put underscore before 'L' as it is same as putting underscore in the end
long hex = 0x_AE_FF_FE_DE; //can't put underscore after 0x
float pi = 1_23._45_67_89F; //can't put underscore just after decimal point(.) 
double amount = 1_257_434_656_.34; //can't put underscore just before decimal point(.)

Thank you for reading through the tutorial. In case of any questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

Sourse: Sain Technology Solutions

For more information please visit: https://codequs.com/