Monday, 29 December 2014

Php session

Php session

Introduce how to use session for checking login.
Session 1: code (database file, login.php, checklogin.php, sessionCSS.css, conn.php, index.php)
Session 2: concept thread
Session 3: explanation

Database
-------------------------------------------------------------------------------------------------------
create database `sessionShop`;

CREATE TABLE admin
(
    name varchar(64) NOT NULL default '',
    password varchar(64) NOT NULL default '',
    primary key(name)
);

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

login.php
-------------------------------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
       <head>
              <title>login</title>
       <link href="sessionCSS.css" type="text/css" rel="stylesheet"/>
       </head>
       <body class="basicbody">
              <table class="tbStyle" cellpadding="0" cellspacing="0" align="center">
                     <tr class="trStyle">
                            <td>
                                   Administrator LogIn
                            </td>
                     </tr>
                     <tr class="trstyleBotm">
                            <td>
                                   <form action="checklogin.php" method="post">
                                          <div class="ContainerDiv">
                                                 <div class="Div90">
                                                        <div class="wordDiv100">
                                                               UserName:
                                                        </div>
                                                        <div class="inputDiv500">
                                                               <input type="text" maxlength="200" name="username" id="username" placeholder="name" autofocus/>
                                                        </div>
                                                 </div>
                                                 <div class="Div90">
                                                        <div class="wordDiv100">
                                                               Password:
                                                        </div>
                                                        <div class="inputDiv500">
                                                               <input type="password" maxlength="200" name="psw" id="password" placeholder="password"/>
                                                        </div>
                                                 </div>
                                                 <div class="Div90">
                                                        <button type="submit" name="Submit" value="submitIt" class="btnStyle">
                                                               Submit
                                                        </button>
                                                        <button type="reset" name="Reset" value="ResetIt" class="btnStyle">
                                                               Reset
                                                        </button>
                                                 </div>
                                          </div>
                                   </form>
                            </td>
                     </tr>
              </table>
       </body>
</html>

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


checklogin.php
-------------------------------------------------------------------------------------------------------
<?php
       require_once 'conn.php';
       session_start();
       $sessionTBname = 'admin';
       $sUserName = $_POST['username'];
       $sPassword = $_POST['psw'];
       $_SESSION['adminName'] = $sUserName;
       $_SESSION['adminPsw'] = $sPassword;
       $execSQL = 'select * from '.$sessionTBname." where name = '".$sUserName."'";
       if ($result = mysql_query($execSQL))
       {
              echo "connect to Table.";
              if ($rs = mysql_fetch_object($result))
              {
                     echo "Record is right.";
                     if ($rs->name == $sUserName && $rs->password == $sPassword && $_SESSION['adminName'] != '' && $_SESSION['adminPsw'] != '')
                     {
                            header("location:index.php");
                     }
                     else
                     {
                            echo "<script>alert('Username, Password check error.');location:href='login.php'</script>";
                     }
              }
              else
              {
                     echo "<script>alert('Record check error.');location:href='login.php'</script>";
              }
             
       }
       else
       {
              echo "can't connect to Table".mysql_error();
              echo "<script>alert('Table connection error.');location:href='login.php';</script>";
       }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
       <head>
              <title>checklogin</title>
       <link href="sessionCSS.css" type="text/css" rel="stylesheet"/>
       </head>
       <body class="basicbody">
             
       </body>
       <?php
              session_unset();
              unset($_SESSION['adminName']);
              unset($_SESSION['adminPsw']);
              mysql_close();
       ?>
</html>

sessionCSS.css
-------------------------------------------------------------------------------------------------------
table.tbStyle
{
       width: 600px;
       height: 400px;
       border: 0px;
       text-align: center;
}

tr.trStyle
{
       width: 600px;
       height: 130px;
       font-family:"Times New Roman", Times, serif;
       font-size:50px;
       font-weight: bolder;
       text-align:center;
       text-shadow: grey 2px 2px;
}

tr.trstyleBotm
{
       width: 600px; height: 270px;
}

div.ContainerDiv
{
       width: 600px; height: 270px;
       margin: 0 auto;
       padding: 0px;
}

div.Div90
{
       width: 600px; height: 90px;
       margin: 0 auto;
       padding: 0px;
}

div.wordDiv100
{
       width: 120px; height: 66px;
       margin: 10px auto;
       padding: 0px;
       float: left;
       text-align: center;
       font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
       font-size:16px;
       font-weight: bolder;
       line-height: 60px;
}

div.inputDiv500
{
       width: 476px; height: 66px;
       margin: 10px auto;
       padding: 0px;
       float: left;
}

input#username
{
       width: 320px; height: 30px;
       margin: 12px auto;
       text-align: left;
       border-radius: 6px;
       -moz-border-radius: 6px;
       -webkit-border-radius: 6px;
       box-shadow: 2px 2px 5px #666;
       -moz-box-shadow: 2px 2px 5px #666;
       -webkit-box-shadow: 2px 2px 5px #666;
       outline: 0px;
}

input#password
{
       width: 320px; height: 30px;
       margin: 12px auto;
       text-align: left;
       border-radius: 6px;
       -moz-border-radius: 6px;
       -webkit-border-radius: 6px;
       box-shadow: 2px 2px 5px #666;
       -moz-box-shadow: 2px 2px 5px #666;
       -webkit-box-shadow: 2px 2px 5px #666;
       outline: 0px;
}

button.btnStyle
{
       width: 60px; height: 30px;
       border-radius: 5px;
       border: 1px #cfdcec solid;
       overflow: hidden;
       box-shadow: 1px 1px 3px gray;
       background: #e2eaf3;
}

button.btnStyle:hover
{
       background: #30588e;
}

conn.php
-------------------------------------------------------------------------------------------------------
<?php
       $sessionUserName = 'root';
       $sessionPassword = '654321';
       $sessionDBname = 'sessionShop';
       $ConnSession = mysql_connect("localhost", $sessionUserName, $sessionPassword) or die("connect wrong --- ".mysql_error());
       mysql_select_db($sessionDBname);
?>

index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
       <head>
              <title>index</title>
       <link href="sessionCSS.css" type="text/css" rel="stylesheet"/>
       </head>
       <body class="basicbody">
              <div class="wordDiv100">Hello World.</div>
       </body>
</html>

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

the thread about this sample is do login page first, then input username and password. Send username and password to checklogin.php. If the username and password is fit, then jump to index.php.

EXPLANATION
conn.php
-------------------------------------------------------------------------------------------------------
<?php
       $sessionUserName = 'root';
       $sessionPassword = '654321';
       $sessionDBname = 'sessionShop';
       $ConnSession = mysql_connect("localhost", $sessionUserName, $sessionPassword) or die("connect wrong --- ".mysql_error());
       mysql_select_db($sessionDBname);
?>
-------------------------------------------------------------------------------------------------------
This file is about connecting to database.

login.php
-------------------------------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
       <head>
              <title>login</title>
       <link href="sessionCSS.css" type="text/css" rel="stylesheet"/>
       </head>
       <body class="basicbody">
              <table class="tbStyle" cellpadding="0" cellspacing="0" align="center">
                     <tr class="trStyle">
                            <td>
                                   Administrator LogIn
                            </td>
                     </tr>
                     <tr class="trstyleBotm">
                            <td>
//post form here
                                   <form action="checklogin.php" method="post">
                                          <div class="ContainerDiv">
                                                 <div class="Div90">
                                                        <div class="wordDiv100">
                                                               UserName:
                                                        </div>
//input username
                                                        <div class="inputDiv500">
                                                               <input type="text" maxlength="200" name="username" id="username" placeholder="name" autofocus/>
                                                        </div>
                                                 </div>
                                                 <div class="Div90">
                                                        <div class="wordDiv100">
                                                               Password:
                                                        </div>
//input password
                                                        <div class="inputDiv500">
                                                               <input type="password" maxlength="200" name="psw" id="password" placeholder="password"/>
                                                        </div>
                                                 </div>
                                                 <div class="Div90">
//submit button and reset button
                                                        <button type="submit" name="Submit" value="submitIt" class="btnStyle">
                                                               Submit
                                                        </button>
                                                        <button type="reset" name="Reset" value="ResetIt" class="btnStyle">
                                                               Reset
                                                        </button>
                                                 </div>
                                          </div>
                                   </form>
                            </td>
                     </tr>
              </table>
       </body>
</html>

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

checklogin.php
-------------------------------------------------------------------------------------------------------
<?php
//connect to database
       require_once 'conn.php';
//start session
       session_start();
       $sessionTBname = 'admin';
//get username from the FORM in login.php
       $sUserName = $_POST['username'];
//get password from the FORM in login.php
       $sPassword = $_POST['psw'];
//assign username and password to current page session
       $_SESSION['adminName'] = $sUserName;
       $_SESSION['adminPsw'] = $sPassword;
//sql select the record according to the username posted.
       $execSQL = 'select * from '.$sessionTBname." where name = '".$sUserName."'";
//get the record
       if ($result = mysql_query($execSQL))
       {
              echo "connect to Table.";
//get the object of the record.
              if ($rs = mysql_fetch_object($result))
              {
                     echo "Record is right.";
//check username and password are correct and session is not null.
                     if ($rs->name == $sUserName && $rs->password == $sPassword && $_SESSION['adminName'] != '' && $_SESSION['adminPsw'] != '')
                     {
                            header("location:index.php");
                     }
                     else
                     {
                            echo "<script>alert('Username, Password check error.');location:href='login.php'</script>";
                     }
              }
              else
              {
                     echo "<script>alert('Record check error.');location:href='login.php'</script>";
              }
             
       }
       else
       {
              echo "can't connect to Table".mysql_error();
              echo "<script>alert('Table connection error.');location:href='login.php';</script>";
       }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
       <head>
              <title>checklogin</title>
       <link href="sessionCSS.css" type="text/css" rel="stylesheet"/>
       </head>
       <body class="basicbody">
             
       </body>
       <?php
              session_unset();
              unset($_SESSION['adminName']);
              unset($_SESSION['adminPsw']);
              mysql_close();
       ?>
</html>


That is all.
Although PHP is not fresh today, it is still there. And php paging is still useful. Let's have a look. There are three portions of this article. To begin with, the result code will be given. To the next part, it is the basic threads of how to do it. The last step is explaining my code.

First thing first, to do paging, create database is basic. And then, the connection file conn.php, paging file paging1.php and css file pagingCSS.css. Named them anything you like, in this case, they named as listed.

Create Database code:
-------------------------------------------------------------------------------------------------------

create database `pagingDB`;

create table tablePages
(
    id bigint(30) unsigned NOT NULL AUTO_INCREMENT,
    name varchar(64) NOT NULL default '' UNIQUE,
    phone varchar(3) NOT NULL default '',
    primary key (id)
)

INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (1,'cao',1);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (2,'ni',2);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (3,'ma',3);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (4,'wocao',4);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (5,'caoni',5);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (6,'mabi',6);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (7,'gan',7);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (8,'niM',8);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (9,'mabiya',9);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (10,'caogan',10);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (11,'diao',11);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (12,'si',12);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (13,'nimabi',13);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (14,'ganya',14);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (15,'caoya',15);
INSERT INTO `tablePages`(`id`, `name`, `phone`) VALUES (16,'baoru',16);


conn.php
-------------------------------------------------------------------------------------------------------
<?php
            $theUser = 'root';
            $thePsw = ‘111111111’;
            $theDBname = 'pagingDB';
            $pagingConn = mysql_connect('localhost', $theUser, $thePsw) or die("connection Error, ".mysql_error());
            mysql_select_db($theDBname);
?>
-------------------------------------------------------------------------------------------------------

paging1.php
-------------------------------------------------------------------------------------------------------
<?php
            echo "The server name is --- ".$_SERVER['SERVER_NAME'];
            require_once 'conn.php';
            $pagingTBname = 'tablePages';
            $sqlSen = "select count(*) as total from ".$pagingTBname;
            $rst = mysql_query($sqlSen);
            $row = mysql_fetch_array($rst);
            $rowsNum = $row['total'];
            mysql_free_result($rst);

            $sqlAllRecords = "select * from ".$pagingTBname;
            $serverRST = mysql_query($sqlAllRecords);
            /*$rowsNum = mysql_num_rows($serverRST);*/
            $columnsNum = mysql_num_fields($serverRST);
            echo "<br>the rows are --- ".$rowsNum." ||| the fields are: ".$columnsNum.".<br>";
            $j = 0;
            while ($j<$columnsNum)
            {
                        $fields[$j] = mysql_field_name($serverRST, $j);
                        $j++;
            }

            $pageSize = 3;
            $initialPage = 1;
            $pageTotalNum = ceil($rowsNum/$pageSize);
           
            if (empty($_GET['page'])||$_GET['page']<$initialPage)
            {
                        $page = $initialPage;
            }
            else
            {
                        $page = $_GET['page'];
            }
            if ($page >= $pageTotalNum)
            {
                        $page = $pageTotalNum;
            }

            $offsetRecordPosition = $pageSize*($page-1);
            $singlePagesRecordNumSQL = "select * from ".$pagingTBname." limit ".$offsetRecordPosition.",".$pageSize;
            $recordsInOnePage = mysql_query($singlePagesRecordNumSQL);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<html>
            <head>
                        <title>paging1</title>
                        <link rel="stylesheet" type="text/css" href="pagingCSS.css">
            </head>
            <body class="basicbody">
                                    <table cellpadding="0" cellspacing="0" align="center" class="tbStyle" border="1">
                                                <tr>
                                                            <?php
                                                                        reset($fields);
                                                                        while (list(,$field_names) = each($fields))
                                                                        {
                                                            ?>
                                                                        <th>
                                                                                    <?php echo "$field_names"; ?>
                                                                        </th>
                                                            <?php
                                                                        }
                                                            ?>
                                                </tr>
                                    <?php
                                                while ($contentRow = mysql_fetch_array($recordsInOnePage))
                                                {
                                    ?>
                                                <tr>
                                                            <?php
                                                                        for ($i=0; $i < $columnsNum; $i++)
                                                                        {
                                                            ?>
                                                                                    <td><?php echo $contentRow[$i]; ?></td>
                                                            <?php
                                                                        }
                                                            ?>
                                                </tr>
                                    <?php
                                                }
                                    ?>
                                    </table>
                                    <div class="divContainer">
                                                <div class="divSlices">
                                                            <a href="paging1.php?page=1" class="aStyle">firstPage</a>
                                                </div>
                                                <div class="divSlices">
                                                            <a href="paging1.php?page=<?php if ($page>$initialPage) {echo $page-1;} else{echo "$initialPage";} ?>" class="aStyle">previousPage</a>
                                                </div>
                                                <div class="divSlices">
                                                            <!-- <a href="" class="aStyle">1234</a> -->
                                                <?php
                                                            for ($i=1; $i <= $pageTotalNum; $i++)
                                                            {
                                                ?>
                                                            <a href="paging1.php?page=<?php echo $i; ?>" class="aStyle"><?php echo $i." "; ?></a>
                                                <?php
                                                            }
                                                ?>
                                                </div>
                                                <div class="divSlices">
                                                            <a href="paging1.php?page=<?php if ($page<$pageTotalNum) {echo $page+1;} else{echo "$pageTotalNum";} ?>" class="aStyle">nextPage</a>
                                                </div>
                                                <div class="divSlices">
                                                            <a href="paging1.php?page=<?php echo $pageTotalNum; ?>" class="aStyle">lastPage</a>
                                                </div>
                                    </div>
            </body>
            <?php
                        /*mysql_close();*/
            ?>
</html>
-------------------------------------------------------------------------------------------------------


pagingCSS.css
-------------------------------------------------------------------------------------------------------
table.tbStyle
{
            width: 210px;
            text-align: center;
}

a.aStyle
{
            text-decoration: none;
            font-family:"Times New Roman", Times, serif;
            font-size:12px;
            font-weight: bolder;
            text-align:center;
}

div.divContainer
{
            width: 416px; height: 28px;
            position: relative;
            top: 20px;
            margin: 0 auto;
            padding: 0px;
}

div.divSlices
{
            width: 80px; height: 20px;
            margin: 0 auto;
            float: left;
            text-align: center;
            background-color: #E0EEEE;
            line-height: 20px;
}
-------------------------------------------------------------------------------------------------------


In this section, the basic thread about how to do it.
First of all, a database is necessary. Create database and table. Insert contents to the table. Nothing has to be explained.
Followed by connection function as every php website does. Connect to database.
The third file is our paging file that is display the information on webpage. It has paging function. It displays few records from database on one webpage and changes to other pages by clicking button links. As can be seen from the image displayed below. The database contains 17 records; every record has 3 columns; 3 records would be listed in one page. You can do these as you like.


The last one is CSS file. It is very usual, nothing to say.


This is the last segment of this article, which will explain the codes. But the only file that needs to be clarified is paging1.php. Others are too plain.

-------------------------------------------------------------------------------------------------------
//find the server name. Useless, doesn’t have to do it.
echo "The server name is --- ".$_SERVER['SERVER_NAME'];
//connect to database
            require_once 'conn.php';
//the table name
            $pagingTBname = 'tablePages';
//count the total number of records in database(SQL).
            $sqlSen = "select count(*) as total from ".$pagingTBname;
//get result by using $sqlSen;
            $rst = mysql_query($sqlSen);
//get one field array to $row from $rst.
            $row = mysql_fetch_array($rst);
//get sum of records.
            $rowsNum = $row['total'];
//release the source.
            mysql_free_result($rst);

//select every thing from database.
            $sqlAllRecords = "select * from ".$pagingTBname;
//get result.
            $serverRST = mysql_query($sqlAllRecords);
//another way to get the sum of records.
            /*$rowsNum = mysql_num_rows($serverRST);*/
//get sum of columns.
            $columnsNum = mysql_num_fields($serverRST);
//display the sum of records. Display sum of column in one records.
            echo "<br>the rows are --- ".$rowsNum." ||| the fields are: ".$columnsNum.".<br>";
-------------------------------------------------------------------------------------------------------

//set an array $fields to collect all fields names.
$j = 0;
            while ($j<$columnsNum)
            {
                        $fields[$j] = mysql_field_name($serverRST, $j);
                        $j++;
            }

//every page displays 3 records.
            $pageSize = 3;
//the beginning page number is 1. Start from page 1, default is page 0;
            $initialPage = 1;
//how many pages required. 17/3 = 6;
            $pageTotalNum = ceil($rowsNum/$pageSize);
           

//If page number is not set or less than 1, display page 1.
            if (empty($_GET['page'])||$_GET['page']<$initialPage)
            {
                        $page = $initialPage;
            }
//otherwise, get page number.
            else
            {
                        $page = $_GET['page'];
            }
//if page number larger or equal the last page, display the last page.
            if ($page >= $pageTotalNum)
            {
                        $page = $pageTotalNum;
            }
-------------------------------------------------------------------------------------------------------
//what is the first record in each webpage?
$offsetRecordPosition = $pageSize*($page-1);
//the range of records for each webpage.
$singlePagesRecordNumSQL = "select * from ".$pagingTBname." limit ".$offsetRecordPosition.",".$pageSize;
//get result of the range of records for each webpage.
(Although the range in page 6 is 3, but only display 2 records, because only last 2 left.)
$recordsInOnePage = mysql_query($singlePagesRecordNumSQL);


-------------------------------------------------------------------------------------------------------
<table cellpadding="0" cellspacing="0" align="center" class="tbStyle" border="1">
                                                <tr>
                                                            <?php
//set array pointer to head.
                                                                        reset($fields);
//display fields name: id, name, phone from database.
                                                                        while (list(,$field_names) = each($fields))
                                                                        {
                                                            ?>
                                                                        <th>
                                                                                    <?php echo "$field_names"; ?>
                                                                        </th>
                                                            <?php
                                                                        }
                                                            ?>
                                                </tr>
                                    <?php
//display different records in respective webpage.
                                                while ($contentRow = mysql_fetch_array($recordsInOnePage))
                                                {
                                    ?>
                                                <tr>
                                                            <?php
//display information ordered by column name.
                                                                        for ($i=0; $i < $columnsNum; $i++)
                                                                        {
                                                            ?>
                                                                                    <td><?php echo $contentRow[$i]; ?></td>
                                                            <?php
                                                                        }
                                                            ?>
                                                </tr>
                                    <?php
                                                }
                                    ?>
                                    </table>

-------------------------------------------------------------------------------------------------------
<div class="divContainer">
//all button are actual links.
            <div class="divSlices">
//linke to webpage itself, and then check the page number.
                        <a href="paging1.php?page=1" class="aStyle">firstPage</a>
</div>
<div class="divSlices">
//if page number larger than 1, the previousPage button will works. The previous page is current page-1.
                        <a href="paging1.php?page=<?php if ($page>$initialPage) {echo $page-1;} else{echo "$initialPage";} ?>" class="aStyle">previousPage</a>
</div>
<div class="divSlices">
            <?php
                        for ($i=1; $i <= $pageTotalNum; $i++)
                        {
                        ?>
            <a href="paging1.php?page=<?php echo $i; ?>" class="aStyle"><?php echo $i." "; ?></a>
<?php
                        }
            ?>
</div>
<div class="divSlices">
                        <a href="paging1.php?page=<?php if ($page<$pageTotalNum) {echo $page+1;} else{echo "$pageTotalNum";} ?>" class="aStyle">nextPage</a>
</div>
<div class="divSlices">
            <a href="paging1.php?page=<?php echo $pageTotalNum; ?>" class="aStyle">lastPage</a>
</div>
</div>

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