Home Backend Development PHP Tutorial How to operate session and database in php

How to operate session and database in php

Jun 09, 2018 am 11:45 AM
mysql php

This article mainly introduces the method of operating session and database in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

The example in this article describes how PHP uses MySQL to save sessions. The specific analysis is as follows:

This function is generally available in many large systems, but it must be separated and analyzed, and the information on the Internet There are not too many. Here I compiled an article to share with you

Using MySQL to save sessions has many advantages over files:

1) It is beneficial to distributed systems, files can only be saved On one machine
2) It is beneficial to systems with large traffic. When using files, each session is saved in a file. The directory will be very large and it will be difficult to find the session file.

To use MySQL to save a session, you must first create the session table:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<?php

$hostname_login = "localhost"; // Server address

$username_login = "root"; // User name

$password_login = ""; // Password

//

$data_name = "session"; // Database name

$login = mysql_pconnect($hostname_login, $username_login, $password_login) or trigger_error(mysql_error(),E_USER_ERROR);

$sql="SHOW DATABASES LIKE &#39;".$data_name."&#39;"; // If it is exist

if($rs_table=mysql_query($sql,$login)) {

  if($rs_value=mysql_fetch_array($rs_table)) {

   echo "数据库已经存在!\n!";

   exit();

  }

}

$sql="CREATE DATABASE $data_name";  

mysql_query($sql); // Crate database

echo "数据库创建成功!\n";

mysql_select_db($data_name, $login);

$sql="CREATE TABLE `sessions` (

`SessionKey` varchar(32) NOT NULL default &#39;&#39;,

`SessionArray` blob NOT NULL,

`SessionExpTime` int(20) unsigned NOT NULL default &#39;0&#39;,

PRIMARY KEY (`SessionKey`),

KEY `SessionKey` (`SessionKey`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8"; //新建数据库 sql语句

mysql_query($sql);

echo "成功新建数据库表!";

?>

Copy after login

MysqlSession class is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

<?php 

class MysqlSession {

// 注意在有使用Session的页面。页面一定要顶格,页面开始处不能留空。

private $DB_SERVER = "localhost"; // 数据库服务器主机名

  private $DB_NAME = ""; // 数据库名字

  private $DB_USER = "root"; // MYSQL 数据库访问用户名

  private $DB_PASS = ""; // MYSQL 数据库访问密码

    

  private $DB_SELECT_DB = "";

//private $SESS_LIFE = 1440; // Session的最大使用时长,单位秒。

private $SESS_LIFE = 0;

function MysqlSession (&$sessionDB) {

  //session_write_close();

  $this->DB_NAME = &$sessionDB;

  $this->SESS_LIFE = get_cfg_var("session.gc_maxlifetime");

  session_module_name(&#39;user&#39;);

  session_set_save_handler(

  array(&$this, &#39;sess_open&#39;),

  array(&$this, &#39;sess_close&#39;),

  array(&$this, &#39;sess_read&#39;),

  array(&$this, &#39;sess_write&#39;),

  array(&$this, &#39;sess_destroy&#39;),

  array(&$this, &#39;sess_gc&#39;)

  );

  session_start();

}

function sess_open($save_path, $session_name){  // 打开数据库连接

  if (! $this->DB_SELECT_DB = mysql_pconnect($this->DB_SERVER, $this->DB_USER, $this->DB_PASS)) {

  echo "SORRY! MYSQL ERROR : Can&#39;t connect to $this->DB_SERVER as $DB_USER";

  echo "MySQL Error: ", mysql_error();

  die;

  }

  if (! mysql_select_db($this->DB_NAME, $this->DB_SELECT_DB)) {

  echo "SORRY! MYSQL ERROR : Unable to select database $this->DB_NAME";

  die;

  }

  return true;

}

function sess_close() {

    return true;

}

function sess_read($SessionKey){ 

    $Query = "SELECT SessionArray FROM sessions WHERE SessionKey = &#39;".$SessionKey."&#39; AND SessionExpTime > " . time();

    // 过期不读取。

    $Result = mysql_query($Query, $this->DB_SELECT_DB);

  if (list($SessionArray) = mysql_fetch_row($Result)) {

     return $SessionArray;

  }

  return false;

}

function sess_write($SessionKey, $VArray) {

  $SessionExpTime = time() + $this->SESS_LIFE;

  // 更新Session过期时间,Session过期时间 = 最后一次更新时间 + Session的最大使用时长

  $SessionArray = addslashes($VArray);

  $Query = "INSERT INTO sessions (SessionKey,SessionExpTime,SessionArray) VALUES (&#39;".$SessionKey."&#39;,&#39;".$SessionExpTime."&#39;,&#39;".$SessionArray."&#39;)";

  $Result = mysql_query($Query, $this->DB_SELECT_DB);

  if (!$Result){

      $Query = "UPDATE sessions SET SessionExpTime = &#39;".$SessionExpTime."&#39;, SessionArray = &#39;".$SessionArray."&#39; WHERE SessionKey = &#39;".$SessionKey."&#39; AND  SessionExpTime > " . time();

      $Result = mysql_query($Query, $this->DB_SELECT_DB);

  

  return $Result;

}

function sess_destroy($SessionKey) {

  $Query = "DELETE FROM sessions WHERE SessionKey = &#39;".$SessionKey."&#39;";

  $Result = mysql_query($Query, $this->DB_SELECT_DB);

  return $Result;

}

function sess_gc($maxlifetime) {

// 这个垃圾清除器系统调用。默认是1440秒清除一次。

//参数可以在PHP.ini里面设置。

  $Query = "DELETE FROM sessions WHERE SessionExpTime < " . time();

  $Result = mysql_query($Query, $this->DB_SELECT_DB);

  return mysql_affected_rows($this->DB_SELECT_DB);

}

}

?>

Copy after login

Usage: Where session_start was originally used, replace it with $session = new MysqlSession ()

Note: The database must be opened before including this program. The database cannot be closed before the main program exits, otherwise an error will occur.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

PHP Mysql jQuery implements password retrieval function

php implements loading fonts and Save

PHP implements Chinese character verification code

The above is the detailed content of How to operate session and database in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

See all articles