PHP writes user information to the database

Source: Internet
Author: User
Tags prepare stmt

Session Advanced App writes user information to the database

First create a database table

Set up session table in experimental database SQLDB for storing data



Create the required files under the root folder (the key is to session,class.php this type of file. Include some methods of listing)


The main use of this method in Session.class.php is Session_set_save_handler (). Data manipulation with PDO. Write to the database table using the class write,

A static method is defined in the class, and its properties are static, so that the session data is written directly to the database, not to the local directory

First set up a session class. Class, you first define some private static properties. Defines the IP. Time and Time to live

<?php//defines Session class    session{    private static $handler =null;    private static $ip =null;    private static $lifetime =null;    private static $time =null;

private static function init ($handler) {self    :: $handler = $handler;//The link representing PDO    //IP first infers that it is not empty self    :: $ip =! Empty ($_server["REMOTE_ADDR"])? $_server["REMOTE_ADDR"]: ' unkown ';    Remove the time to live from the profile self    :: $lifetime =ini_get (' session.gc_maxlifetime ');    Self:: $time =time ();    }

The next step is to define how to open the session

Defines the method of opening session static function start (PDO $pdo) {    self::init ($pdo);  Initializes the private method    Session_set_save_handler (    array (__class__, "open"),    Array (__class__, "close"),    Array (__class__, "read"),    Array (__class__, "write"),    Array (__class__, "destroy"), Array (    __class__, "GC")    );    Session_Start ();}


In the open session there are open, close, read, write, Destory, GC methods. The following are the main definitions of these methods

Open () and close () methods

public static function open ($path, $name) {    return true;} public static function Close () {    return true;}

When defining these methods, the most important is the write () and read () methods, since this is read directly from the database or written, using the PDO database preprocessing method

Read (): Advanced line PDO preprocessing. Then in the obtained record, to infer whether the IP is the IP in the database, whether the data is out of date has expired, is not a successful read out

    public static function read ($PHPSESSID) {    $sql = ' Select Phpsessid,update_time,client_ip,data from session where Phpsessid=? ";    //pdo preprocessing    $stmt =self:: $handler->prepare ($sql);    $stmt->execute (Array ($PHPSESSID));    Gets a record    if (! $result = $stmt->fetch (PDO::FETCH_ASSOC)) {    return ';    }    Infer that the current access IP is the IP if of the database    (self:: $ip! = $result ["Client_ip"]) {self    ::d Estroy ($PHPSESSID);  Destroy user    return ';    }    Inference is not expired    if (($result ["update_time"] + self:: $lifetime) < self:: $time) {self    ::d Estroy ($PHPSESSID);    return ';    }    return $result [' data '];  Successful read out    }


Write (): The same method of writing is also more important, it is necessary to infer whether the data passed in is empty, assuming that null is not inserted

    public static function Write ($PHPSESSID, $data) {    $sql = ' Select Phpsessid,update_time,client_ip,data from session where phpsessid=?

"; $stmt =self:: $handler->prepare ($sql); $stmt->execute (Array ($PHPSESSID)); if ($result = $stmt->fetch (PDO::FETCH_ASSOC)) { //Delay 30 Update if ($result [' data ']! = $data | | Self:: $time > ($ result[' Update_time ']+30) { //Update data statement $sql = "Uptate session set update_time=?", Data=?

where phpsessid=? "; $stm =self:: $handler->prepare ($sql); $stm->execute (Array (self:: $time, $data, $PHPSESSID)); } } else{ //Infer whether the data passed in is empty. Null does not insert if (!empty ($data)) { $sql = "INSERT into session (Phpsessid,update_time,client_ip,data) values (?

,?,?,?

)"; Insert value with?

References $sth =self:: $handler->prepare ($sql); $sth->execute (Array ($PHPSESSID, self:: $time, Self:: $ip, $data)); Must use array } } to return true;


The next step is data destruction.

Same destory () and GC ()

Destory (): Data deletion

GC (): Garbage collection

    public static function Destroy ($PHPSESSID) {    $sql = ' Delete from session where phpsessid=?

"; $stmt =self:: $handler->prepare ($sql); $stmt->execute (Array ($PHPSESSID)); return true; } private static function GC ($lifetime) { $sql = "Delete from session where Update_time <?

"; $stmt =self:: $handler->prepare ($sql); $stmt->execute (Array (self:: $time-$lifetime)); return true; } }


Finally, throw an exception and call the session class

    try{    $pdo =new PDO ("Mysql:host=localhost;dbname=sqldb", "root", "heyifeng19930924");    } catch (Pdoexception $e) {    echo $e->getmessage ();    }    Call Session class    Session::start ($PDO);


In the test file. The same way as the advanced use of the session (that is, the test file of the previous blog)

Just include this type of file in the Include file

Namely: include "session.class.php";



Test results, assuming that the data inserted successfully, query the table information, in the database display:


That is, passing the value of the column Phpsessid


After removing the undo. Query table Display


The value of PHPSESSID is revoked.













PHP writes user information to the database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.