How to operate session and database in 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:
<?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 '".$data_name."'"; // 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 '', `SessionArray` blob NOT NULL, `SessionExpTime` int(20) unsigned NOT NULL default '0', PRIMARY KEY (`SessionKey`), KEY `SessionKey` (`SessionKey`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8"; //新建数据库 sql语句 mysql_query($sql); echo "成功新建数据库表!"; ?>
MysqlSession class is as follows:
<?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('user'); session_set_save_handler( array(&$this, 'sess_open'), array(&$this, 'sess_close'), array(&$this, 'sess_read'), array(&$this, 'sess_write'), array(&$this, 'sess_destroy'), array(&$this, 'sess_gc') ); 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'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 = '".$SessionKey."' 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 ('".$SessionKey."','".$SessionExpTime."','".$SessionArray."')"; $Result = mysql_query($Query, $this->DB_SELECT_DB); if (!$Result){ $Query = "UPDATE sessions SET SessionExpTime = '".$SessionExpTime."', SessionArray = '".$SessionArray."' WHERE SessionKey = '".$SessionKey."' AND SessionExpTime > " . time(); $Result = mysql_query($Query, $this->DB_SELECT_DB); } return $Result; } function sess_destroy($SessionKey) { $Query = "DELETE FROM sessions WHERE SessionKey = '".$SessionKey."'"; $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); } } ?>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

View the MySQL database with the following command: Connect to the server: mysql -u Username -p Password Run SHOW DATABASES; Command to get all existing databases Select database: USE database name; View table: SHOW TABLES; View table structure: DESCRIBE table name; View data: SELECT * FROM table name;

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

Copying a table in MySQL requires creating new tables, inserting data, setting foreign keys, copying indexes, triggers, stored procedures, and functions. The specific steps include: creating a new table with the same structure. Insert data from the original table into a new table. Set the same foreign key constraint (if the original table has one). Create the same index. Create the same trigger (if the original table has one). Create the same stored procedure or function (if the original table is used).

Common reasons why Navicat cannot connect to the database and its solutions: 1. Check the server's running status; 2. Check the connection information; 3. Adjust the firewall settings; 4. Configure remote access; 5. Troubleshoot network problems; 6. Check permissions; 7. Ensure version compatibility; 8. Troubleshoot other possibilities.

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.
