search
HomeBackend DevelopmentPHP TutorialHow to operate MySQL database and session dialogue in PHP

This article mainly introduces the method of using PHP to operate MySQL database and session dialogue. Friends who are interested 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 found in many large systems, but it must be separated and analyzed. It is reliable online. There is not much information. 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 only Can 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.

//////使用MySQL保存会话首先要创建session表:
<?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 "成功新建数据库表!";
?>
/////////MysqlSession 类如下:
<?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); 
} 
}
?>
//用法:在原来使用 session_start 的地方,替换成 $session = new MysqlSession () 
//注意:包含此程序前要打开数据库,主程序退出前不能关闭数据库,否则会出错。

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

Related recommendations:

PHP simulates the response class method in asp

Three kinds of php Recursive function implementation method

php judgment on the current encoding and corresponding encoding conversion implementation skills

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

Statement
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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 Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.